Difference between datetime.combine() and pytz.localize()

穿精又带淫゛_ 提交于 2020-01-05 02:35:09

问题


I am a bit puzzled by the following behavior. Suppose I use datetime.combine() to construct a timezone-aware object:

>>> date
datetime.date(2018, 10, 17)
>>> time
datetime.time(6, 0)
>>> tz
<DstTzInfo 'Europe/Berlin' LMT+0:53:00 STD>
>>> datetime.combine(date, time, tzinfo=tz)
datetime.datetime(2018, 10, 17, 6, 0, tzinfo=<DstTzInfo 'Europe/Berlin' LMT+0:53:00 STD>)

or I use pytz.localize() to do the same:

>>> tz.localize(datetime.combine(date, time))
datetime.datetime(2018, 10, 17, 6, 0, tzinfo=<DstTzInfo 'Europe/Berlin' CEST+2:00:00 DST>)

Note how the tzinfo’s timezone name and offset have changed. I am unable to find a proper documentation for that behavior. The pytz documentation says

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

So what exactly is going on here? (Somewhat related questions are here or here.)


回答1:


You just found out (again) that you should never directly add timezone information when creating timezone-aware datetimes. Always use tz.localize().

The problem you are seeing is because datetime.combine doesn't adjust the tzinfo object to the actual datetime. It still assumes the timezone information of the first valid date in this timezone, which was in the late 1800's and happened to be 0:53:00 off from UTC.



来源:https://stackoverflow.com/questions/52733868/difference-between-datetime-combine-and-pytz-localize

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