简体   繁体   中英

Converting a string month day, year to mm/dd/yyyy

I need to covert a string which contains date information (eg, November 3, 2020 ) into date format (ie, 11/03/2020 ). I wrote

df['Date']=pd.to_datetime(df['Date']).map(lambda x: x.strftime('%m/%d/%y'))

where Date is

November 3, 2020
June 26, 2002
July 02, 2010

and many other dates, but I found the error ValueError: NaTType does not support strftime.

You can use pandas.Series.dt.strftime , which handles the NaT :

import pandas as pd

dates = ['November 3, 2020',
         'June 26, 2002',
         'July 02, 2010',
         'NaT']

dates = pd.to_datetime(dates)
df = pd.DataFrame(dates, columns=['Date'])
df['Date'] = df['Date'].dt.strftime('%m/%d/%y')

Output:

       Date
0  11/03/20
1  06/26/02
2  07/02/10
3       NaN

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