Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

datetime and timezone conversion with pytz - mind blowing behaviour

I'm trying to convert timezone aware datetime object to UTC and then back to it's original timezone. I have a following snippet

t = datetime(     2013, 11, 22, hour=11, minute=0,     tzinfo=pytz.timezone('Europe/Warsaw') ) 

now in ipython:

In [18]: t Out[18]: datetime.datetime(     2013, 11, 22, 11, 0, tzinfo=<DstTzInfo 'Europe/Warsaw' WMT+1:24:00 STD> ) 

and now let's try to do conversion to UTC and back. I would expect to have the same representation as:

In [19]: t.astimezone(pytz.utc).astimezone(pytz.timezone('Europe/Warsaw')) Out[19]: datetime.datetime(     2013, 11, 22, 10, 36, tzinfo=<DstTzInfo 'Europe/Warsaw' CET+1:00:00 STD> ) 

Yet we see that Out[18] and Out[19] differ. What's going on?

like image 438
yakxxx Avatar asked Aug 30 '13 20:08

yakxxx


People also ask

What does pytz timezone do?

Introduction. pytz brings the Olson tz database into Python. This library allows accurate and cross platform timezone calculations using Python 2.4 or higher. It also solves the issue of ambiguous times at the end of daylight saving time, which you can read more about in the Python Library Reference ( datetime.

Is Python DateTime timezone aware?

Timezone-aware objects are Python DateTime or time objects that include timezone information. An aware object represents a specific moment in time that is not open to interpretation.

What is Tzinfo DateTime?

tzinfo is an abstract base class. It cannot be instantiated directly. A concrete subclass has to derive it and implement the methods provided by this abstract class. The instance of the tzinfo class can be passed to the constructors of the datetime and time objects.


1 Answers

The documentation http://pytz.sourceforge.net/ states "Unfortunately using the tzinfo argument of the standard datetime constructors 'does not work' with pytz for many timezones." The code:

t = datetime(     2013, 5, 11, hour=11, minute=0,     tzinfo=pytz.timezone('Europe/Warsaw') ) 

doesn't work according to this, instead you should use the localize method:

t = pytz.timezone('Europe/Warsaw').localize(         datetime(2013, 5, 11, hour=11, minute=0)) 
like image 185
James K Avatar answered Oct 05 '22 21:10

James K