Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to correctly change format of date where day and month is changes in position in Data Frame in Python Pandas?

I have DataFrame in Pandas like below:

data type of COL1 is "object"

COL1
------
1-05-2019
22-04-2019  
5-06-2019

And I need to have this column as data type "object" and in format dd-mm-yyyy for example 01-05-2019.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

When I use code like follow: df["COL2"] = df["COL1"].astype("datetime64").dt.strftime('%d-%m-%Y')

I have result like below:

COL1       | COL2
-----------|------
1-05-2019  | 05-01-2019
22-04-2019 | 22-04-2019
5-06-2019  | 06-05-2019

As you can see, for dates from COL1 like: 1-05-2019 and 5-06-2019 my code change position of day and month but for dates like 22-04-2019 works correctly.

I need to have an output like below in "object" data type:

COL1       | COL2
-----------|------
1-05-2019  | 01-05-2019
22-04-2019 | 22-04-2019
5-06-2019  | 05-06-2019

How can I do taht in Python Pandas ?

>Solution :

Convert COL1 to a datetime of a specific format, then format back to a string:

import pandas as pd

df = pd.DataFrame(['1-05-2019','22-04-2019','5-06-2019'], columns=['COL1'])
print(df)
print()
df["COL2"]  = pd.to_datetime(df["COL1"], format='%d-%m-%Y').dt.strftime('%d-%m-%Y')
print(df)

Output:

         COL1
0   1-05-2019
1  22-04-2019
2   5-06-2019

         COL1        COL2
0   1-05-2019  01-05-2019
1  22-04-2019  22-04-2019
2   5-06-2019  05-06-2019
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading