【问题标题】:How to convert normal string to datetime in Pandas如何在 Pandas 中将普通字符串转换为日期时间
【发布时间】:2017-03-30 12:56:08
【问题描述】:

我有来自 .csv 文件的超过数百万个数据点的普通字符串,格式如下:

Datetime
22/12/2015  17:00:00
22/12/2015  18:00:00

我加载到 pandas 并尝试使用 pandas.to_datetime(df['Datetime']) 转换为日期时间格式。但是,我得到的新时间序列数据不正确。在转换过程中会产生一些新的日期时间。例如 2016-12-11 23:30:00 不包含在原始数据中。

【问题讨论】:

  • 你能多展示一点你的代码吗?
  • 感谢您的评论。我得到了如下答案,我的代码现在可以工作了。
  • 很高兴你得到它 =)

标签: python pandas datetime


【解决方案1】:

我使用 panda 已经有一段时间了,但在您的示例中,您的日期格式与 csv 中的示例行不同:

yyyy-mm-dd hh:mm:ss

而不是

mm/dd/yyyy hh:mm:ss

to_datetime 函数采用参数“格式”,如果这是原因,这应该会有所帮助。

【讨论】:

  • 非常感谢。在加载到 pandas DataFrame 之前,我按照您在 csv 文件中的建议更改了格式,现在效果很好:)
  • @Panda-in-Code 你应该接受这个作为答案。
【解决方案2】:

您想使用选项dayfirst=True

pd.to_datetime(df.Datetime, dayfirst=True)

这个:

Datetime
22/12/2015  17:00:00
22/12/2015  18:00:00
11/12/2015  23:30:00

转换为

0   2015-12-22 17:00:00
1   2015-12-22 18:00:00
2   2015-12-11 23:30:00
Name: Datetime, dtype: datetime64[ns]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-05
    • 2019-03-14
    • 1970-01-01
    • 2022-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-19
    相关资源
    最近更新 更多