日期时间和时区转换与pytz - 心灵吹拂行为 [英] datetime and timezone conversion with pytz - mind blowing behaviour
问题描述
我正在尝试将时区知道 datetime
对象转换为UTC,然后返回到原始时区。我有以下代码片段
I'm trying to convert timezone aware datetime
object to UTC and then back to it's original timezone. I have a following snippet
t = datetime(
2013, 11, 22, hour=11, minute=0,
tzinfo=pytz.timezone('Europe/Warsaw')
)
现在在ipython中:
now in ipython:
In [18]: t
Out[18]: datetime.datetime(
2013, 11, 22, 11, 0, tzinfo=<DstTzInfo 'Europe/Warsaw' WMT+1:24:00 STD>
)
现在让我们尝试转换为UTC并返回。我希望具有相同的表示方式:
and now let's try to do conversion to UTC and back. I would expect to have the same representation as:
In [19]: t.astimezone(pytz.utc).astimezone(pytz.timezone('Europe/Warsaw'))
Out[19]: datetime.datetime(
2013, 11, 22, 10, 36, tzinfo=<DstTzInfo 'Europe/Warsaw' CET+1:00:00 STD>
)
然而,我们看到 [18]
和 Out [19]
不同。发生了什么?
Yet we see that Out[18]
and Out[19]
differ. What's going on?
推荐答案
文档 http://pytz.sourceforge.net/ 指出不幸的是,使用标准datetime构造函数的tzinfo参数对于许多时区而言并不适用于pytz。代码
The documentation http://pytz.sourceforge.net/ states "Unfortunately using the tzinfo argument of the standard datetime constructors 'does not work' with pytz for many timezones." The code
t = datetime(
2013, 5, 11, hour=11, minute=0,
tzinfo=pytz.timezone('Europe/Warsaw')
)
根据这个工作,您应该使用本地化方法:
doesn't work according to this, instead you should use the localize method:
t = pytz.timezone('Europe/Warsaw').localize(
datetime(2013, 5, 11, hour=11, minute=0))
这篇关于日期时间和时区转换与pytz - 心灵吹拂行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!