与熊猫的不良日期识别to_datetime

时间:2020-09-04 07:44:30

标签: python pandas datetime

我需要从Excel文件中识别日期:

    [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

我使用:

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

但是碰巧表的第一行中的日期被替换为月份:

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

第二个还可以:

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

我需要为日期添加一个模式。

2 个答案:

答案 0 :(得分:1)

使用参数格式,对于比赛日使用%d,对于几个月%m,对于YY使用%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  

或使用参数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  

答案 1 :(得分:0)

这将解决它:

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