Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pytz localize vs datetime replace

I'm having some weird issues with pytz's .localize() function. Sometimes it wouldn't make adjustments to the localized datetime:

.localize behaviour:

>>> tz <DstTzInfo 'Africa/Abidjan' LMT-1 day, 23:44:00 STD>  >>> d datetime.datetime(2009, 9, 2, 14, 45, 42, 91421)  >>> tz.localize(d) datetime.datetime(2009, 9, 2, 14, 45, 42, 91421,                    tzinfo=<DstTzInfo 'Africa/Abidjan' GMT0:00:00 STD>) >>> tz.normalize(tz.localize(d)) datetime.datetime(2009, 9, 2, 14, 45, 42, 91421,                   tzinfo=<DstTzInfo 'Africa/Abidjan' GMT0:00:00 STD>) 

As you can see, time has not been changed as a result of localize/normalize operations. However, if .replace is used:

>>> d.replace(tzinfo=tz) datetime.datetime(2009, 9, 2, 14, 45, 42, 91421,                    tzinfo=<DstTzInfo 'Africa/Abidjan' LMT-1 day, 23:44:00 STD>) >>> tz.normalize(d.replace(tzinfo=tz)) datetime.datetime(2009, 9, 2, 15, 1, 42, 91421,                   tzinfo=<DstTzInfo 'Africa/Abidjan' GMT0:00:00 STD>) 

Which seems to make adjustments into datetime.

Question is - which is correct and why other's wrong?

like image 568
Art Avatar asked Sep 04 '09 14:09

Art


People also ask

What does pytz localize do?

localize() pytz. localize() is useful for making a naive timezone aware. it is useful when a front-end client sends a datetime to the backend to be treated as a particular timezone (usually UTC).

How do I remove Tzinfo from datetime?

To remove timestamp, tzinfo has to be set None when calling replace() function. First, create a DateTime object with current time using datetime. now(). The DateTime object was then modified to contain the timezone information as well using the timezone.

What does pytz do in Python?

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.

What is pytz UTC?

The pytz package encourages using UTC for internal timezone representation by including a special UTC implementation based on the standard Python reference implementation in the Python documentation. The UTC timezone unpickles to be the same instance, and pickles to a smaller size than other pytz tzinfo instances.


1 Answers

localize just assumes that the naive datetime you pass it is "right" (except for not knowing about the timezone!) and so just sets the timezone, no other adjustments.

You can (and it's advisable...) internally work in UTC (rather than with naive datetimes) and use replace when you need to perform I/O of datetimes in a localized way (normalize will handle DST and the like).

like image 126
Alex Martelli Avatar answered Oct 08 '22 00:10

Alex Martelli