首页 > 解决方案 > change multiple date time formats to single format in pandas dataframe

问题描述

I have a DataFrame with multiple formats as shown below

0      07-04-2021
1      06-03-1991
2      12-10-2020
3      07/04/2021
4      05/12/1996

What I want is to have one format after applying the Pandas function to the entire column so that all the dates are in the format

date/month/year

What I tried is the following

date1 = pd.to_datetime(df['Date_Reported'], errors='coerce', format='%d/%m/%Y')

But it is not working out. Can this be done? Thank you

标签: pandasdataframe

解决方案


try with dayfirst=True:

date1=pd.to_datetime(df['Date_Reported'], errors='coerce',dayfirst=True)

output of date1:

0   2021-04-07
1   1991-03-06
2   2020-10-12
3   2021-04-07
4   1996-12-05
Name: Date_Reported, dtype: datetime64[ns]

If needed:

date1=date1.dt.strftime('%d/%m/%Y')

output of date1:

0    07/04/2021
1    06/03/1991
2    12/10/2020
3    07/04/2021
4    05/12/1996
Name: Date_Reported, dtype: object

推荐阅读