Python dateutil反转的时区偏移标志?

R J*_*R J 6 python datetime python-dateutil

有谁知道为什么python的dateutil在解析datetime字段时会反转GMT偏移的符号?

显然,这个特性不仅是dateutil而且是其他解析函数的已知结果.但是,除非应用预处理黑客,否则会导致INCORRECT日期时间结果:

from dateutil import parser

jsDT = 'Fri Jan 02 2015 03:04:05.678910 GMT-0800'
python_datetime = parser.parse(jsDT)
print(python_datetime)
>>> 2015-01-02 03:04:05.678910+08:00

jsDT = 'Fri Jan 02 2015 03:04:05.678910 GMT-0800'
if '-' in jsDT:
    jsDT = jsDT.replace('-','+')
elif '+' in jsDT:
    jsDT = jsDT.replace('+','-')
python_datetime = parser.parse(jsDT)
print(python_datetime)
>>> 2015-01-02 03:04:05.678910-08:00
Run Code Online (Sandbox Code Playgroud)

jfs*_*jfs 8

它似乎dateutil在这里使用POSIX风格的标志.它与Python无关.其他软件也是如此.来自tz数据库:

# We use POSIX-style signs in the Zone names and the output abbreviations,
# even though this is the opposite of what many people expect.
# POSIX has positive signs west of Greenwich, but many people expect
# positive signs east of Greenwich.  For example, TZ='Etc/GMT+4' uses
# the abbreviation "GMT+4" and corresponds to 4 hours behind UT
# (i.e. west of Greenwich) even though many people would expect it to
# mean 4 hours ahead of UT (i.e. east of Greenwich).
Run Code Online (Sandbox Code Playgroud)

tz数据库几乎用于所有地方.

例:

$ TZ=Etc/GMT-8 date +%z
+0800
Run Code Online (Sandbox Code Playgroud)

你可能期望一个不同的时区:

>>> from datetime import datetime
>>> import pytz
>>> pytz.timezone('America/Los_Angeles').localize(datetime(2015, 1, 2, 3, 4, 5, 678910), is_dst=None).strftime('%Y-%m-%d %H:%M:%S.%f %Z%z')
'2015-01-02 03:04:05.678910 PST-0800'
Run Code Online (Sandbox Code Playgroud)

注意:PST不是GMT.

虽然dateutil使用POSIX风格的标志,即使是PST时区缩写:

>>> from dateutil.parser import parse
>>> str(parse('2015-01-02 03:04:05.678910 PST-0800'))
'2015-01-02 03:04:05.678910+08:00'
Run Code Online (Sandbox Code Playgroud)

datetime.strptime() 在Python 3中"正确"解释它:

$ TZ=America/Los_Angeles python3                                               
...
>>> from datetime import datetime
>>> str(datetime.strptime('2015-01-02 03:04:05.678910 PST-0800', '%Y-%m-%d %H:%M:%S.%f %Z%z'))
'2015-01-02 03:04:05.678910-08:00'
Run Code Online (Sandbox Code Playgroud)

注意标志.

尽管由于POSIX风格的标志造成了混乱; dateutil行为不太可能改变.看dateutil错误:"GMT + 1"被解析为"GMT-1"和@Lennart Regebro的回复:

以这种方式解析GTM + 1实际上是Posix规范的一部分.因此,这是一个功能,而不是错误.

看看如何TZ在POSIX规范中定义环境变量,glibc使用类似的定义.

目前尚不清楚为什么dateutil使用TZ类似POSIX 的语法来解释时间字符串中的时区信息.语法不完全相同,例如,POSIX语法需要分号:hh[:mm[:ss]]在输入中不存在的utc偏移量中.


Dan*_*haw 2

dateutil.parser.parse 的源代码解释了这一点。

检查是否有 GMT+3 或 BRST+3 之类的内容。请注意,它并不意味着“我是 GMT 后 3 小时”,而是“我的时间 +3 是 GMT”。如果找到,我们将反转逻辑,以便时区解析代码能够得到正确的结果。

以及进一步的评论:

对于 GMT+3 之类的时间,时区不是GMT