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?
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).
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With