简体   繁体   中英

How to convert string date to pandas date and time

I have following dataframe in pandas

 order_id     order_date
 12           2020 July 4,5:40 pm
 13           2020 July 4,5:55 pm
 14           2020 July 4,6:00 pm

I want to convert the date in following format

  order_id     order_date
 12           2020-07-04 17:40:00
 13           2020-07-04 17:55:00
 14           2020-07-04 18:00:00

I have tried following, but it does not seem to be working.

df['clean_date'] = df['order_date'].apply(lambda x: pd.to_datetime(x).strftime('%m-%d-%Y %H:%M')[0])

How can I do this in pandas?

You don't need to add strftime . Just by applying pd.to_datetime solves your problem:

>>> df['clean_date'] = df.order_date.apply(lambda x: pd.to_datetime(x))

>>> df
   order_id           order_date          clean_date
0        12  2020 July 4,5:40 pm 2020-07-04 17:40:00
1        13  2020 July 4,5:55 pm 2020-07-04 17:55:00
2        14  2020 July 4,6:00 pm 2020-07-04 18:00:00

Just use pd.to_datetime

df['order_date']=pd.to_datetime(df['order_date'])

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