gpt4 book ai didi

python - dateutil 反转时区偏移符号?

转载 作者:太空狗 更新时间:2023-10-30 00:49:18 28 4
gpt4 key购买 nike

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

显然这个特征是 known outcome不仅是 dateutil,还有其他解析函数。但这会导致不正确日期时间结果,除非应用了预处理 hack:

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

最佳答案

dateutil 似乎在这里使用了 POSIX 风格的符号。它与 Python 无关。其他软件也可以。来自 the tz database :

# 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).

The tz database is used almost everywhere .

例子:

$ TZ=Etc/GMT-8 date +%z
+0800

您可能期望不同的时区:

>>> 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'

注意: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'

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'

注意标志。

尽管由于 POSIX 风格的符号而造成混淆; dateutil 行为不太可能改变。请参见 dateutil 错误:"GMT+1" is parsed as "GMT-1"和@Lennart Regebro 的回复:

Parsing GTM+1 this way is actually a part of the Posix specification. This is therefore a feature, and not a bug.

看看如何TZ environment variable is defined in the POSIX specification , glibc 使用 similar definition .

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

关于python - dateutil 反转时区偏移符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31078749/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com