问题
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