1

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?

run_the_race
  • 1,344
  • 2
  • 36
  • 62
  • 1
    Maybe the deprecation shim can get you going? https://pytz-deprecation-shim.readthedocs.io/en/latest/ (besides, with UTC you don't need to localize, even with pytz. You can just set the tzinfo directly) – FObersteiner Dec 06 '21 at 18:16
  • `pytz: The Fastest Footgun in the West` ... so funny =) – run_the_race Dec 06 '21 at 18:27

2 Answers2

5

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.

Wolfgang Kuehn
  • 12,206
  • 2
  • 33
  • 46
0

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.

run_the_race
  • 1,344
  • 2
  • 36
  • 62