7

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:

Martin Thoma
  • 124,992
  • 159
  • 614
  • 958
  • 2
    Possible duplicate of [Why doesn't pytz localize() produce a datetime object with tzinfo matching the tz object that localized it?](https://stackoverflow.com/questions/24359540/why-doesnt-pytz-localize-produce-a-datetime-object-with-tzinfo-matching-the-t) – Sean Breckenridge May 21 '18 at 06:52
  • The other answer also shows why it's that value: [LMT](https://en.wikipedia.org/wiki/Local_mean_time). And I really don't see the benefit to large section titles in such a simple question. – jonrsharpe May 21 '18 at 07:04
  • The reason its like that isn't really a programming question. It has to do with the [history of german timezones](https://www.postgresql.org/message-id/OFD3976F87.F787752A-ONC1257B67.00473B00-C1257B67.00482D32%40ppi.de). – Sean Breckenridge May 21 '18 at 07:07
  • @SeanBreckenridge Ah, nice! [This Wiki article](https://de.wikipedia.org/wiki/Gesetz_betreffend_die_Einführung_einer_einheitlichen_Zeitbestimmung) goes in the right direction! What I still miss there is how the local time was / is calculated. – Martin Thoma May 21 '18 at 07:17

1 Answers1

6

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194