【问题标题】:How to convert to datetime if the format of dates changes gradually through the column?如果日期格式通过列逐渐变化,如何转换为日期时间?
【发布时间】:2020-02-20 18:22:27
【问题描述】:

df.head():

    start_date  end_date

0   03.09.2013  03.09.2025
1   09.08.2019  14.05.2020
2   03.08.2015  03.08.2019
3   31.03.2014  31.03.2019
4   02.02.2015  02.02.2019
5   21.08.2019  21.08.2024

当我执行 df.tail() 时:

        start_date          end_date

30373   2019-07-05 00:00:00 2023-07-05 00:00:00
30374   2019-06-11 00:00:00 2023-06-11 00:00:00
30375   19.01.2017 2020-02-09 00:00:00 #these 2 start dates are just same as in head
30376   11.12.2009 2011-12-11 00:00:00
30377   2019-07-30 00:00:00 2023-07-30 00:00:00

当我这样做时

df[start_date] = pd.to_datetime(df[start_date]) 

某些日期将月份转换为天。 通过列格式不一致。如何正确转换?

【问题讨论】:

    标签: pandas datetime type-conversion


    【解决方案1】:

    使用dayfirst=True参数:

    df['start_date'] = pd.to_datetime(df['start_date'], dayfirst=True) 
    

    或者通过http://strftime.org/指定格式:

    df['start_date'] = pd.to_datetime(df['start_date'], format='%d.%m.%Y') 
    

    df['start_date'] = pd.to_datetime(df['start_date'], dayfirst=True)
    df['end_date'] = pd.to_datetime(df['end_date'], dayfirst=True)
    print (df)
      start_date   end_date
    0 2013-09-03 2025-09-03
    1 2019-08-09 2020-05-14
    2 2015-08-03 2019-08-03
    3 2014-03-31 2019-03-31
    4 2015-02-02 2019-02-02
    5 2019-08-21 2024-08-21
    

    【讨论】:

    • @kaban - 我想因为我多次解决这个问题,所以有时我会花一些时间寻找我的解决方案为什么不起作用。原因和你一样。
    猜你喜欢
    • 2020-03-04
    • 1970-01-01
    • 2019-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-03
    相关资源
    最近更新 更多