Strange behavior.

I make some changes in the time zone, and I get really strange results. Basically, switching between time zones that differ only in whole hours, I still get inappropriate results. For example:

from datetime import datetime from pytz import timezone datetime(2013, 12, 27, 20, 0, 0, tzinfo=timezone('Europe/Bucharest'))\ .astimezone(timezone('Europe/Berlin')).replace(tzinfo=None) 

gives me

 datetime.datetime(2013, 12, 27, 19, 16) 

(the time difference between Bucharest and Berlin is 1 hour, so I have to get 19:00 - instead I get 19:16)

I probably missed something really obvious, but I can't figure it out. What am I doing wrong?

+8
python pytz
source share
2 answers

As stated in the pytz documentation :

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

Indeed, this is not the expected result, the time zone is incorrect:

 >>> datetime(2013, 12, 27, 20, 0, 0, tzinfo=timezone('Europe/Bucharest')) datetime.datetime(2013, 12, 27, 20, 0, tzinfo=<DstTzInfo 'Europe/Bucharest' BMT+1:44:00 STD>) 

It is explained that the pytz constructor specified by the timezone('Europe/Bucharest') does not check when the timezone offset should be taken into account, and these things change over time. pytz simply uses a previously known definition, which is often incorrect:

 >>> timezone('Europe/Bucharest') <DstTzInfo 'Europe/Bucharest' BMT+1:44:00 STD> 

It seems that this time zone was used until 1931 .

There is no such problem when working with UTC and converting using astimezone (for display only in accordance with the recommendations):

 >>> datetime(2013, 12, 27, 20, 0, 0, tzinfo=pytz.utc)\ .astimezone(timezone('Europe/Bucharest')) datetime.datetime(2013, 12, 27, 22, 0, tzinfo=<DstTzInfo 'Europe/Bucharest' EET+2:00:00 STD>) 

Then you will get the expected result:

 >>> datetime(2013, 12, 27, 20, 0, 0, tzinfo=pytz.utc)\ .astimezone(timezone('Europe/Bucharest'))\ .astimezone(timezone('Europe/Berlin'))\ .replace(tzinfo=None) datetime.datetime(2013, 12, 27, 21, 0) 
+7
source share

Today I ran into the same problem and ended up solving it using the @jfs answer placed in the comment of the currently accepted answer. To help anyone else find this in the future, here is a brief example of what does and doesn't work:

 from datetime import datetime import pytz naive = datetime.now() la_tz = pytz.timezone("America/Los_Angeles") # this doesn't work with_tz = naive.replace(tzinfo=la_tz) converted_to_utc = with_tz.astimezone(pytz.utc) print(converted_to_utc) # this does work with_tz = la_tz.localize(naive) converted_to_utc = with_tz.astimezone(pytz.utc) print(converted_to_utc) 
0
source share

All Articles