简体   繁体   中英

Convert date format using python

I am trying to convert the date format from a column in an specific format in python

Input Data:

    Date 

01/10/2020
01-mar-2020
1-june-2019
01/01/2021
1/11/2020

Output looking for:

    Date 

2020-10-01
2020-03-01
2019-06-01
2021-01-01
2020-11-01

Code been using so far:

df['Date'] = pd.to_datetime(df['Date'], errors='coerce')
df['Date'] = df['Date'].dt.strftime('%Y-%m-%d')

With the above script i am getting this output:

   Date
2020-01-10
2020-03-01
2019-06-01
2021-01-01
2020-01-11 

but its not giving the output as what i am trying to find.

Just use dayfirst parameter of to_datetime() method and set that equal to True :

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

Finally:

df['Date'] = df['Date'].dt.strftime('%Y-%m-%d')

Now if you print df or df['Date'] you will get your desired output:

0    2020-10-01
1    2020-03-01
2    2019-06-01
3    2021-01-01
4    2020-11-01

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