【问题标题】:I have this format as object 2020-11-18 10:36:29.772234 +0000 UTC, want to convert to date time我将此格式作为对象 2020-11-18 10:36:29.772234 +0000 UTC,想转换为日期时间
【发布时间】:2021-03-05 15:18:16
【问题描述】:

2020-11-20 23:07:59.381081 +0000 UTC

我正在使用 pandas 读取 csv 文件,并且在数据框中有一个时间戳列是对象。我无法转换为日期时间,也无法将 +0000 UTC 读取为格式

我尝试了以下方法:

datetimeObj = datetime.strptime('2020-11-21 22:16:25.389601 +0000 UTC', '%Y-%m-%d %H:%M:%S.%f %Z')

但是 %Z 给了我错误。 对 python 和 Pandas 世界的初学者的任何建议 ?

【问题讨论】:

标签: python pandas date datetime timestamp


【解决方案1】:

您还必须在 %Z 之前添加 %z。

  • %z 表示 +HHMM 或 -HHMM 形式的偏移量。
  • %Z 指时区名称。

试试这个:

datetime_object = datetime.strptime('2020-11-20 23:07:59.381081 +0000 UTC', '%Y-%m-%d %H:%M:%S.%f %z %Z')

【讨论】:

  • 有趣的是,%Z 实际上什么也没做,只是确保它是 UTC 或 GMT。其他时区缩写会引发错误。 %z 将 "+0000" 解析为 UTC,stackoverflow.com/a/64981768/10197418pandas.to_datetime 中,不能同时使用两者。
【解决方案2】:

假设您在 pandas DataFrame 中有该格式的日期时间字符串,我建议您删除 +0000,因为 pd.to_datetime 不会同时解析 +0000UTC em>。

import pandas as pd

df = pd.DataFrame({'timestamp':["2020-11-20 23:07:59.381081 +0000 UTC"]})

df['datetime'] = pd.to_datetime(df['timestamp'].str.replace(" +0000", "", regex=False))

# df['datetime']
# 0   2020-11-20 23:07:59.381081+00:00
# Name: datetime, dtype: datetime64[ns, UTC]

为什么不直接去掉UTC?与 +0000 的 UTC 偏移相比,它是明确的。 +0000 也可能源自恰好在时间戳中表示的时间具有 UTC+0 的时区。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-23
    • 2021-10-14
    • 1970-01-01
    • 1970-01-01
    • 2019-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多