pytz 的奇怪时区问题
>>> import pytz
>>> pytz.timezone('Asia/Hong_Kong')
<DstTzInfo 'Asia/Hong_Kong' LMT+7:37:00 STD>
七个小时37分钟的偏移?这有点奇怪,有人遇到同样的问题吗?
实际上,我之间的行为不同
import pytz
from datetime import datetime
hk = pytz.timezone('Asia/Hong_Kong')
dt1 = datetime(2012,1,1,tzinfo=hk)
dt2 = hk.localize(datetime(2012,1,1))
if dt1 > dt2:
print "Why?"
>>> import pytz
>>> pytz.timezone('Asia/Hong_Kong')
<DstTzInfo 'Asia/Hong_Kong' LMT+7:37:00 STD>
A seven hour and 37 minute offset? This is a little strange, does anyone experience the same issue?
In fact I'm getting different behavior between
import pytz
from datetime import datetime
hk = pytz.timezone('Asia/Hong_Kong')
dt1 = datetime(2012,1,1,tzinfo=hk)
dt2 = hk.localize(datetime(2012,1,1))
if dt1 > dt2:
print "Why?"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
时区和偏移量多年来一直在变化。 pytz 创建时区对象时传递的默认区域名称和偏移量是该区域最早可用的名称和偏移量,有时它们看起来有点奇怪。当您使用
localize
将区域附加到日期时,正确的区域名称和偏移量将被替换。仅使用datetime
构造函数将区域附加到日期并不允许其正确调整。Time zones and offsets change over the years. The default zone name and offset delivered when pytz creates a timezone object are the earliest ones available for that zone, and sometimes they can seem kind of strange. When you use
localize
to attach the zone to a date, the proper zone name and offset are substituted. Simply using thedatetime
constructor to attach the zone to the date doesn't allow it to adjust properly.将近10年后来这里,我认为值得注意的是,我们现在可以专门利用Python 3.9+标准库来处理时区,而没有“本地化陷阱”。
使用 Zoneinfo 设置并替换Tzinfo,但是您喜欢,例如:
注释
pytz
替代方案,如果您无法使用
Zoneinfo
:diessInfo
的语义相同的语义Coming here nearly 10 years later, I think it's worth a note that we can now exclusively utilize the Python 3.9+ standard library to handle time zones, without a "localize trap".
Use the zoneinfo module to set and replace the tzinfo however you like, ex:
Notes
pytz
Alternatives, if you're not able to use
zoneinfo
:zoneinfo
虽然我确信时区的历史变化是一个因素,但将 pytz 时区对象传递给 DateTime 构造函数会导致奇怪的行为,即使对于自启动以来没有经历任何变化的时区也是如此。
创建
日期时间对象,然后对其进行本地化,产生预期
结果
While I'm sure historic changes in timezones are a factor, passing pytz timezone object to the DateTime constructor results in odd behavior even for timezones that have experienced no changes since their inception.
produces
Creating the datetime object then localizing it produced expected results
produces