将datetime打印为pytz.timezone(“ Etc / GMT-5”)会产生错误的结果 [英] Printing datetime as pytz.timezone("Etc/GMT-5") yields incorrect result
问题描述
请考虑以下示例,在该示例中,我采用了一个简单的日期时间,使其在UTC中变为时区,然后转换为UTC-5:
Consider the following example, where I take a naive datetime, make it timezone aware in UTC, and then convert to UTC-5:
d1 = datetime.datetime(2019,3,7, 7,45)
d2 = pytz.utc.localize(d1)
print(f'UTC : {d2}')
d3 = d2.astimezone(pytz.timezone('Etc/GMT-5'))
print(f'UTC-5: {d3}')
其输出为:
UTC : 2019-03-07 07:45:00+00:00
UTC-5: 2019-03-07 12:45:00+05:00
我希望 UTC -5
时间为 02:45
,但是5小时的偏移量是添加到UTC,而不是减去。
I would have expected the UTC-5
time to be 02:45
, but the 5 hour offset is being added to UTC, rather than subtracted.
问题:
- 为什么
'Etc / GMT-5'
应用于UTC +5小时而不是-5小时的偏移量? - 如何从
UTC
到UTC-5
?
- Why is the
'Etc/GMT-5'
offset applied to UTC +5 hours instead of -5 hours? - How can I convert from
UTC
toUTC-5
?
推荐答案
您正在使用 pytz
,而不仅仅是Python的 datetime
。
像dateutil ,pytz 使用Olson tz数据库。
You are using pytz
, not just Python's datetime
.
Like dateutil, pytz uses the Olson tz database.
Olson tz数据库定义了 Etc / GMT + N
符合POSIX风格的时区:
The Olson tz database defines Etc/GMT+N
timezones which conform with the POSIX style:
以
开头的区域名称 Etc / GMT的符号与标准ISO 8601约定相反。在
中的 Etc区域中,GMT以西的区域带有正号,而东部的区域则带有
负号(例如, Etc / GMT-14比GMT早14小时。)
those zone names beginning with "Etc/GMT" have their sign reversed from the standard ISO 8601 convention. In the "Etc" area, zones west of GMT have a positive sign and those east have a negative sign in their name (e.g "Etc/GMT-14" is 14 hours ahead of GMT.)
因此,要将UTC转换为偏移量为-5的时区,可以使用 Etc / GMT + 5
:
import datetime as DT
import pytz
naive = DT.datetime(2019, 3, 7, 7, 45)
utc = pytz.utc
gmt5 = pytz.timezone('Etc/GMT+5')
print(utc.localize(naive).astimezone(gmt5))
# 2019-03-07 02:45:00-05:00
这篇关于将datetime打印为pytz.timezone(“ Etc / GMT-5”)会产生错误的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!