Home > Blockchain >  Pandas: How to Format 2 types of Dates?
Pandas: How to Format 2 types of Dates?

Time:09-20

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:

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.

CodePudding user response:

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
  • Related