繁体   English   中英

Pandas - to_datetime 不解析 utc

[英]Pandas - to_datetime not parsing utc

我有一个 csv 文件,其中有一个名为“阅读时间”的日期时间字段,看起来像下面的“2020-09-01 00:06:52 +0000 UTC”。

在 Pandas 中使用以下任何 to_datetime function 时,根据我使用的 function arguments 出现以下错误:

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”吗?

提前致谢。

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

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

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

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

您包括 %Z 作为时区名称 (UTC),但没有 %z 作为 UTC 偏移量 (+0000)。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM