简体   繁体   中英

Convert Month name and Year (Such as Jul-15) to date - Python

my column values are like this " Jul-15", "Jun-15" and etc... The data type is object.

I want to change the data type to date and the values to date. I tried

df["Time Period"] = df["Time Period"].apply(lambda x: datetime.strptime(x, '%m-Y'))

but it is giving me the time data 'Jul-15' does not match format '%m-Y' .

Any help is much appreciated.

  • Three letters month names are matched by %b , not %m .
  • Two digits years are matched by %y , not Y

While you are at it, ditch .apply and use the vectorized to_datetime to gain speed:

df['Time Period'] = pd.to_datetime(df['Time Period'], format='%b-%y')

See strftime directives supported by pandas .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM