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

Pandas: How to Format 2 types of Dates?

How to convert these two different date-formats to one?

I’m using:

df["date"] = pd.to_datetime(df["date"], format = "%d-%m")

and it returns:

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

ValueError: time data '22.03.' does not match format '%m-%d' (match)

…My date column has two different types of dates displayed:

   0          22.03.
   1          22.03.
              ...    
   448    10.09.2021
   449    09.09.2021

I don’t need to display the year, so DATE.MONTH -format would be enough.

>Solution :

Create datetiems in both formats with errors='coerce' and replace missing values another Series:

s1 = pd.to_datetime(df["date"], format = "%d.%m.", errors='coerce')
s2 = pd.to_datetime(df["date"], format = "%d.%m.%Y", errors='coerce')
df["date"] = s1.fillna(s2)

print (df)
          date
0   1900-03-22
1   1900-03-22
448 2021-09-10
449 2021-09-09
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