Convert datetime.datetime from UTC to CEST one hour to less

Question:

If I run the following code I convert the datetime.datetime from utc to cest, but it does not work right. Correct would be if it would change from 21:29 to 23:29 because the time difference is 2 hours

from_zone = tz.gettz('UTC')
to_zone = tz.gettz('CEST')

created_at
Out[302]: datetime.datetime(2020, 1, 30, 21, 29, 34)

utc.replace(tzinfo=from_zone)
Out[303]: datetime.datetime(2020, 1, 30, 21, 29, 34, tzinfo=tzwin('UTC'))

utc.astimezone(to_zone)
Out[304]: datetime.datetime(2020, 1, 30, 22, 29, 34, tzinfo=datetime.timezone(datetime.timedelta(seconds=3600), 'Mitteleuropäische Zeit'))
Asked By: padul

||

Answers:

For correct localization, provide a IANA time zone name, e.g.

to_zone = tz.gettz('Europe/Berlin')

Bringing up @GiacomoCatenazzi’s comment, note that the IANA time zone (here: Europe/Berlin) relates to a geographical region whilst the associated "abbreviations" (here: CET/CEST) relate to offsets from UTC during certain periods of the year. Multiple geographical time zones can share the same offset to UTC, e.g. Europe/Berlin and Europe/Paris even change between CET and CEST simultaneously in 2020.

But: the other way round, it’s 1) ambiguous or 2) even invalid:

  1. multiple geographical regions can have the CEST UTC offset
    during certain times
  2. for example there is no CEST on 2020-01-01 (although countries somewhere else in the world might have UTC+2 at that time…)
Answered By: FObersteiner