bad date recognition with pandas to_datetime

Viewed 67

I need to recognize dates from an Excel file:

    [1399 rows x 8 columns]
      Pož. č.         Vytvořil(A)            Vyžádáno Odesláno Dne                 Status Číslo objednávky    Celkem   new_date
10    1012717  xxxxxxxxx xxxxxxxx      yyyyyy yyyyyyy   12. 08. 20  Přijato (Sent to RFQ)         CO744765    140.00 2020-12-08
11    1009920  xxxxxxxxx xxxxxxxx      yyyyyy yyyyyyy   14. 08. 20  Přijato (Sent to RFQ)         CO748621     92.00 2020-08-14
12     993689      yyyyyy yyyyyyy  xxxxxxxxx xxxxxxxx   24. 07. 20                Přijato         CO738902  12125.04 2020-07-24
14     989011  xxxxxxxxx xxxxxxxx      yyyyyy yyyyyyy   22. 07. 20                Přijato         CO733551    337.94 2020-07-22

I use :

df['new_date'] = pd.to_datetime(df['Odesláno Dne'])

but it happens that the day is swapped with the month in the first row of the table:

 pd.to_datetime('12. 08. 20')
 Out: Timestamp('2020-12-08 00:00:00')

The second is okay:

pd.to_datetime('14. 08. 20')
Out: Timestamp('2020-08-14 00:00:00')

I thing need to add a pattern for the date.

2 Answers

Use parameter format, for match days use %d, for months %m and for YY use %y:

df['new_date'] = pd.to_datetime(df['Odesláno Dne'], format='%d. %m. %y')
print (df)
    Po. č.         Vytvořil(A)            Vyžádáno Odesláno Dne  \
10  1012717  xxxxxxxxx xxxxxxxx      yyyyyy yyyyyyy   12. 08. 20   
11  1009920  xxxxxxxxx xxxxxxxx      yyyyyy yyyyyyy   14. 08. 20   
12   993689      yyyyyy yyyyyyy  xxxxxxxxx xxxxxxxx   24. 07. 20   
14   989011  xxxxxxxxx xxxxxxxx      yyyyyy yyyyyyy   22. 07. 20   

                   Status Číslo objednávky    Celkem   new_date  
10  Přijato (Sent to RFQ)         CO744765    140.00 2020-08-12  
11  Přijato (Sent to RFQ)         CO748621     92.00 2020-08-14  
12                Přijato         CO738902  12125.04 2020-07-24  
14                Přijato         CO733551    337.94 2020-07-22  

Or use parameter dayfirst=True:

df['new_date'] = pd.to_datetime(df['Odesláno Dne'], dayfirst=True)
print (df)
    Po. č.         Vytvořil(A)            Vyžádáno Odesláno Dne  \
10  1012717  xxxxxxxxx xxxxxxxx      yyyyyy yyyyyyy   12. 08. 20   
11  1009920  xxxxxxxxx xxxxxxxx      yyyyyy yyyyyyy   14. 08. 20   
12   993689      yyyyyy yyyyyyy  xxxxxxxxx xxxxxxxx   24. 07. 20   
14   989011  xxxxxxxxx xxxxxxxx      yyyyyy yyyyyyy   22. 07. 20   

                   Status Číslo objednávky    Celkem   new_date  
10  Přijato (Sent to RFQ)         CO744765    140.00 2020-08-12  
11  Přijato (Sent to RFQ)         CO748621     92.00 2020-08-14  
12                Přijato         CO738902  12125.04 2020-07-24  
14                Přijato         CO733551    337.94 2020-07-22  

This will solve it:

df['new_date'] = pd.to_datetime(df['Odesláno Dne'],format="%d/%m/%y")
Related