Why do I get the offset 0:53 for timezone Europe/Berlin?

流过昼夜 提交于 2021-02-17 05:15:25

问题


Example Code

from datetime import datetime, timezone
import pytz

tzstring = 'Europe/Berlin'
t1 = datetime(2016, 6, 16, 2, 0, tzinfo=pytz.timezone(tzstring))
t2 = datetime(2016, 6, 16, 2, 0, tzinfo=timezone.utc).astimezone(pytz.timezone(tzstring))

Observed

print(t1): 2016-06-16 02:00:00+00:53
print(t2): 2016-06-16 04:00:00+02:00

Expected

print(t1): 2016-06-16 04:00:00+02:00  # does not match expectation
print(t2): 2016-06-16 04:00:00+02:00  # matches expectation

Question

Can somebody please explain that to me?

Other questions:

  • Why doesn't pytz localize() produce a datetime object with tzinfo matching the tz object that localized it? only asks for an explanation to "where in the code does it come from". My question is more in the direction: "Why is it that off?" - so likely a bit of history will be in an answer that I accept.

回答1:


I wouldn't like to say I can explain it as such, but it is documented to not work. From the pytz home page:

This library only supports two ways of building a localized time. The first is to use the localize() method provided by the pytz library. This is used to localize a naive datetime (datetime with no timezone information)

(Example)

The second way of building a localized time is by converting an existing localized time using the standard astimezone() method.

(Example)

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

>>> datetime(2002, 10, 27, 12, 0, 0, tzinfo=amsterdam).strftime(fmt)
'2002-10-27 12:00:00 LMT+0020'

It is safe for timezones without daylight saving transitions though, such as UTC

I suspect the representation of time zones in pytz is just incompatible with what the datetime constructor uses.

Rather than chase the exact details, I suspect it's more practical just to accept it doesn't work and use the alternatives suggested.



来源:https://stackoverflow.com/questions/50443305/why-do-i-get-the-offset-053-for-timezone-europe-berlin

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