0

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.

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.