【问题标题】:Pandas - to_datetime not parsing utc熊猫 - to_datetime 不解析 UTC
【发布时间】:2022-01-24 22:47:03
【问题描述】:

我有一个 csv 文件,其中包含一个名为“阅读时间”的日期时间字段,类似于以下“2020-09-01 00:06:52 +0000 UTC”。

在 Pandas 中使用以下任何 to_datetime 函数时,根据我使用的函数参数,我会收到以下错误:

df['Reading Time'] =  pd.to_datetime(df['Reading Time'], format='%Y-%m-%d %H:%M:%S')
df['Reading Time'] =  pd.to_datetime(df['Reading Time'], format='%Y-%m-%d %H:%M:%S', exact=False)
df['Reading Time'] =  pd.to_datetime(df['Reading Time'], format='%Y-%m-%d %H:%M:%S %Z')
df['Reading Time'] =  pd.to_datetime(df['Reading Time'], format='%Y-%m-%d %H:%M:%S %Z', exact=False)

ValueError: time data 2020-09-01 00:06:52 +0000 UTC doesn't match format specified

如果我然后尝试“强制”参数...

df['Reading Time'] =  pd.to_datetime(df['Reading Time'], format='%Y-%m-%d %H:%M:%S %Z', errors='coerce')

...所有阅读时间值都返回为“NaT”

解析前是否需要先去掉“+0000 UTC”?

提前致谢。

【问题讨论】:

    标签: python pandas datetime string-to-datetime


    【解决方案1】:

    问题可能是您提供的格式。

    时区名称 (UTC) 包含 %Z,但 UTC 偏移量 (+0000) 不包含 %z。

    df['Reading Time'] =  pd.to_datetime(df['Reading Time'], format='%Y-%m-%d %H:%M:%S %z %Z')
    

    试试吧。

    这里是格式参数的文档:https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior

    【讨论】:

    • 这是@aj-davies 的建议。我尝试了上述并收到以下错误:ValueError:无法同时解析 %Z 和 %z
    【解决方案2】:

    我遇到了同样的问题,Pandas 没有同时解析 %z 和 %Z,所以我使用这个正则表达式从字符串末尾删除时区名称:

    strs = df['Reading Time'].apply(lambda x: re.sub(' \w+$','',x))
    df['Reading Time'] = pd.to_datetime( strs )
    

    正则表达式匹配一个空格,后跟任意数量的字母,直到字符串的末尾,如 UTC、EST 等。然后 Pandas 将自动解析格式,而无需您指定。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-12
      • 2018-06-05
      • 2020-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-09
      相关资源
      最近更新 更多