2

With this I'm struggling for some hours now. The code is much larger than the example I'm providing here, but it breaks down to this:

I have a datetime object that is naive and I want to convert it to UTC time, but that doesn't work as expected.

import datetime
import pytz

# Following is a naive datetime object, but we know the user meant
# timezone Europe/Zurich

zurich = datetime.datetime(2016, 1, 8, 7, 10)
# datetime.datetime(2016, 1, 8, 7, 10)

# So I'm now converting it to a datetime object which is aware of the
# timezone

zurich = zurich.replace(tzinfo=pytz.timezone('Europe/Zurich'))
# datetime.datetime(2016, 1, 8, 7, 10, tzinfo=<DstTzInfo 'Europe/Zurich' BMT+0:30:00 STD>)

# Let's convert to UTC

zurich = zurich.astimezone(pytz.utc)
# datetime.datetime(2016, 1, 8, 6, 40, tzinfo=<UTC>)

The offset of Zurich compared to UTC time is +01:00 (Daylight saving time) or +02:00 (Summer time). Why is Python thinking it is +00:30?!

Any help is highly appreciated (I'm starting to pull out my hair already).

Daniel
  • 1,515
  • 3
  • 17
  • 30
  • Found it in the docs here: [http://pytz.sourceforge.net/#example-usage](http://pytz.sourceforge.net/#example-usage) Unfortunately using the tzinfo argument of the standard datetime constructors ‘’does not work’’ with pytz for many timezones. – Daniel Jan 08 '16 at 18:11
  • It can not work and even the syntax is not sufficient, because a timezone Continent/City can not be blindly replaced without knowledge if it is in a DST time or STD time. Therefore a smart function from pytz must be called that gets the time and zone, applies the current goverment rules and customizes the zone to "CET+1:00 STD" or "CEST+2:00 DST". The standard datetime methods have no callback to tzinfo to customize it and even the `is_dst` pameter must be used one hour before and after the point change from DST to STD in order to convert the time unambiguously. – hynekcer Jan 08 '16 at 18:39

1 Answers1

1

I found this answer on a similar issue, and if I rewrite your code this other way, it seems to address your request

import datetime
import pytz
zurich = pytz.timezone('Europe/Zurich').localize(datetime.datetime(2016,1,8,7,10), is_dst=None)
zurich = zurich.astimezone(pytz.utc)
# datetime.datetime(2016, 1, 8, 6, 10, tzinfo=<UTC>)
Community
  • 1
  • 1
sal
  • 3,515
  • 1
  • 10
  • 21