python - 奇怪的 .astimezone 行为

标签 python pytz

我正在做一些时区转换,我得到了非常奇怪的结果。基本上在仅相差整小时的时区之间进行转换,我仍然得到非完整的结果。例如:

from datetime import datetime
from pytz import timezone

datetime(2013, 12, 27, 20, 0, 0, tzinfo=timezone('Europe/Bucharest'))\
    .astimezone(timezone('Europe/Berlin')).replace(tzinfo=None)

给我

datetime.datetime(2013, 12, 27, 19, 16)

(布加勒斯特和柏林之间的时差是 1 小时,所以我应该到 19:00,而不是 19:16)

我可能遗漏了一些非常明显的东西,但我无法弄清楚。我做错了什么?

最佳答案

pytz documentation 指定:

Unfortunately using the tzinfo argument of the standard datetime constructors ‘’does not work’’ with pytz for many timezones.

确实,这不是预期的结果,时区错误:

>>> datetime(2013, 12, 27, 20, 0, 0, tzinfo=timezone('Europe/Bucharest'))
datetime.datetime(2013, 12, 27, 20, 0,
    tzinfo=<DstTzInfo 'Europe/Bucharest' BMT+1:44:00 STD>)

这解释了 pytz 构造函数给定 timezone('Europe/Bucharest') 时区不检查 何时 时区偏移量应该是考虑过,这些事情往往会随着时间而改变。 pytz 只是使用较早的已知定义,这通常是错误的:

>>> timezone('Europe/Bucharest')
<DstTzInfo 'Europe/Bucharest' BMT+1:44:00 STD>

看起来这个时区被使用了until 1931 .

使用 UTC 时间并使用 astimezone 转换这些时间时没有这样的问题(仅出于推荐的显示目的):

>>> datetime(2013, 12, 27, 20, 0, 0, tzinfo=pytz.utc)\
    .astimezone(timezone('Europe/Bucharest')) 
datetime.datetime(2013, 12, 27, 22, 0,
    tzinfo=<DstTzInfo 'Europe/Bucharest' EET+2:00:00 STD>)

然后你得到预期的结果:

>>> datetime(2013, 12, 27, 20, 0, 0, tzinfo=pytz.utc)\
    .astimezone(timezone('Europe/Bucharest'))\
    .astimezone(timezone('Europe/Berlin'))\
    .replace(tzinfo=None)
datetime.datetime(2013, 12, 27, 21, 0)

关于python - 奇怪的 .astimezone 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20804837/

相关文章:

Python-Django 时区无法正常工作

python - pytz:_utcoffset 对伊朗有错误的值(value)

python datetime.astimezone 行为不正确?

python - 在django模型中默认输入本地时间的当前日期时间

Notepad++ 中的 Python 语法高亮显示

python - 在 Python 中缩放列表列表的列

python - Pylint 中模块 'QApplication' 错误中没有名称 'PyQt5.QtWidgets'

python - 使用 Selenium 在 Python 中循环 XPath 元素位置

Python Flask-Restful 应用程序与 Kubernetes - 连接被拒绝

python - 添加到数据库时时间值略有偏差