Home > Enterprise >  Convert an aware timezone to UIC timezone with zoneinfo (migration away from pytz)
Convert an aware timezone to UIC timezone with zoneinfo (migration away from pytz)

Time:12-10

I am using Python 3.8, so I am using https://pypi.org/project/backports.zoneinfo/ to get zoneinfo. Django is deprecating the use of pytz so I am performing the change from pytz to zoneinfo

With pytz one would do from pytz import UTC. The python documentation gets it from datetime.timezone.utc' (and this does not have a localize` method).

How does one perform the equivalent of this: pytz.UTC.localize(my_datetime, is_dst=None) With zoneinfo?

CodePudding user response:

pytz.localize is for naive datetimes (datetime with no timezone information) only, so

import datetime
import pytz
my_datetime = datetime.datetime(2021, 10, 31, 2)
pytz.UTC.localize(my_datetime, is_dst=None)
# -> datetime.datetime(2021, 10, 31, 2, 0, tzinfo=<UTC>)

The corresponding pytz-less construct is

my_datetime.replace(tzinfo=datetime.timezone.utc)
# -> datetime.datetime(2021, 10, 31, 2, 0, tzinfo=datetime.timezone.utc)

Note: Do not use my_datetime.astimezone(timezone.utc) as this will assume my_datetime is represented in the system time zone.

CodePudding user response:

The link @MrFuppes provides: https://blog.ganssle.io/articles/2018/03/pytz-fastest-footgun.html explains that pytz with its localize method was none standard. Now with zone info we can use an easy standard API without worry about shooting oneself in the foot:

pytz.UTC.localize(my_datetime, is_dst=None)

becomes

my_datetime.astimezone(timezone.utc)

And date arithmetic now works even with none UTC datetimes.

  • Related