Convert month, day in string to date in Python

Viewed 59

I have 2 columns as month and day in my dataframe which are of the datatypes objects. I want to sort those in ascending order (Jan, Feb, Mar) but in order to do that, I need to convert them to date format. I tried using the following code, and some more but nothing seems to work.

ff['month'] = dt.datetime.strptime(ff['month'],format='%b')

and

ff['month'] = pd.to_datetime(ff['month'], format="%b")

Data Frame

Any help would be appreciated. Thank you

1 Answers

This works to convert Month Names to Integers:

import datetime as dt
        
ff['month'] = [dt.datetime.strptime(m, "%b").month for m in ff['month']]

(Basically, you're just passing strings one by one to the first function you mentioned, to make it work.) You can then manipulate (e.g. sort) them.

Working with dataframe:

ff['month'] = ff['month'].apply(lambda x: dt.datetime.strptime(x, "%b"))
    
ff = ff.sort_values(by=['month'])
ff['month'] = ff['month'].apply(lambda x: x.strftime("%b"))
Related