datetime and timezone conversion with pytz - mind blowing behaviour

情到浓时终转凉″ 提交于 2019-11-28 22:31:37

问题


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

now in ipython:

In [18]: t
Out[18]: datetime.datetime(
    2013, 11, 22, 11, 0, tzinfo=<DstTzInfo 'Europe/Warsaw' WMT+1:24:00 STD>
)

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

Yet we see that Out[18] and Out[19] differ. What's going on?


回答1:


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


来源:https://stackoverflow.com/questions/18541051/datetime-and-timezone-conversion-with-pytz-mind-blowing-behaviour

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!