当TZ在环境中时,Python时间解析失败 [英] Python time-parsing fails, when TZ is in the environment

查看:68
本文介绍了当TZ在环境中时,Python时间解析失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下简单脚本:

from datetime import datetime as DT

ts  = 'Mon Aug 17 12:49:28 EDT 2020'
fmt = '%a %b %d %H:%M:%S %Z %Y'
dts = DT.strptime(ts, fmt)
print(dts)

正常工作,当我简单地用它调用Python时:

works normally, when I simply invoke Python with it:

% python3.7 t.py
2020-08-17 12:49:28

但是,如果我向环境添加不同的时区,脚本将失败:

However, if I add a different timezone to the environment, the script fails:

% env TZ=UTC python3.7 t.py
Traceback (most recent call last):
  File "t.py", line 5, in <module>
    dts = DT.strptime(ts, fmt)
  File "/opt/lib/python3.7/_strptime.py", line 577, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "/opt/lib/python3.7/_strptime.py", line 359, in _strptime
    (data_string, format))
ValueError: time data 'Mon Aug 17 12:49:28 EDT 2020' does not match format '%a %b %d %H:%M:%S %Z %Y'

我尝试使用较早的Python版本2.7和3.6并得到相同的错误。即使将 TZ 设置为 EDT 也不起作用,尽管 America / New_York (这是我计算机的 / etc / localtime )似乎还可以。

I tried with earlier Python-versions -- 2.7 and 3.6 -- and got the same error. Even setting the TZ to EDT does not work, although the value of America/New_York (which is my computer's /etc/localtime) seems Ok.

如何可靠地解析此类时间戳?

How can such timestamps be parsed reliably?

推荐答案

我建议将 dateutil 的parser.parse与时区映射dict:

I suggest using dateutil's parser.parse with a time zone mapping dict:

import dateutil
ts = 'Mon Aug 17 12:49:28 EDT 2020'

# add more time zone names / abbreviations as key-value pairs here:
tzmapping = {'EDT': dateutil.tz.gettz('US/Eastern')}

dt = dateutil.parser.parse(ts, tzinfos=tzmapping)

print(dt)
print(repr(dt))
# 2020-08-17 12:49:28-04:00
# datetime.datetime(2020, 8, 17, 12, 49, 28, tzinfo=tzfile('US/Eastern'))

时区名称的缩写本质上是模棱两可的,不会被%Z 解析。 UTC和GMT例外-但是,请注意这一点! %Z 接受,例如文字 UTC但这不会产生可识别的日期时间对象。同样,dateutil的解析器比标准库的datetime.strptime更好。

Time zone name abbreviations are inherently ambiguous and won't be parsed by %Z. Exceptions are UTC and GMT - however, also be careful with that! %Z accepts e.g. a literal "UTC" but it doesn't result in an aware datetime object. Again, dateutil's parser does a better job than the standard lib's datetime.strptime.

这篇关于当TZ在环境中时,Python时间解析失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆