【问题标题】:Convert string to datetime将字符串转换为日期时间
【发布时间】:2017-08-31 14:25:30
【问题描述】:

我有一个简单的问题 - 似乎以前被问过很多次(例如,参见 hereherehere)。尽管如此,我无法解决它。

我得到了一个从 csv 文件中读取的 pandas 数据框。它包含名称为 start-plan 的列,其字符串格式为 '05-04-2017'(2017 年 4 月 5 日)。据我了解,它是%d-%m-%Y 形式的欧洲日期时间。 这是我的工作:

df = pd.read_csv('activities.csv')

这是数据框头部的样子:

print(df.head())

       start-plan start-actual    end-plan  end-actual  user  late
0  12-01-2017   16-01-2017  11-02-2017  10-02-2017     1     0
1  11-05-2017   15-05-2017  10-06-2017  18-06-2017     2     1
2  20-08-2017   20-08-2017  19-09-2017  05-10-2017     3     1
3  10-12-2017   10-12-2017  09-01-2018  08-01-2018     1     0
4  25-04-2017   25-04-2017  25-05-2017  26-05-2017     4     0

我尝试像这样转换列:

pd.to_datetime(pd.Series('start-plan'), format='%d-%m-%y')

我收到一条错误消息,指出 time data 'start-plan' does not match format '%d-%M-%Y' (match)

我做错了什么?此外,我有几列格式相同,我想转换。有没有可能一次性全部转换?

【问题讨论】:

    标签: string python-3.x date pandas type-conversion


    【解决方案1】:

    您正在使用'start-plan' 制作pd.Series

    试试:

    pd.to_datetime(df['start-plan'], format='%d-%m-%y')
    

    您也可以使用选项dayfirst=True

    你可以像这样一口气搞定

    cols = ['start-plan', 'start-actual', 'end-plan', 'end-actual']
    df = df[cols].apply(
        pd.to_datetime, dayfirst=True
    ).join(df.drop(cols, 1))
    
    print(df)
    
      start-plan start-actual   end-plan end-actual  user  late
    0 2017-01-12   2017-01-16 2017-02-11 2017-02-10     1     0
    1 2017-05-11   2017-05-15 2017-06-10 2017-06-18     2     1
    2 2017-08-20   2017-08-20 2017-09-19 2017-10-05     3     1
    3 2017-12-10   2017-12-10 2018-01-09 2018-01-08     1     0
    4 2017-04-25   2017-04-25 2017-05-25 2017-05-26     4     0
    

    【讨论】:

    • 我也试过df['start-plan'] = pd.to_datetime(df['start-plan'])。两者似乎都有效!谢谢!
    • @Rachel 那是因为pd.to_datetime 能够推断。如果它碰巧是模棱两可的,你最好是具体的。
    • @Rachel,即使我认为熊猫会推断但尝试 df.loc[1, 'start-plan'].day。它返回 5 作为天而不是 11。所以 piRsquared 的答案是要走的路
    • 回报时间小家伙
    猜你喜欢
    • 2015-09-17
    • 1970-01-01
    • 2022-08-18
    相关资源
    最近更新 更多