Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an aware datetime's timezone to UTC with zoneinfo (migration away from pytz)

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?

like image 505
run_the_race Avatar asked Oct 17 '25 11:10

run_the_race


2 Answers

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.

like image 95
Wolfgang Kuehn Avatar answered Oct 20 '25 03:10

Wolfgang Kuehn


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.

For @Wolfgang Kuehn

Python 3.9.17 (main, Jun  6 2023, 20:11:21) 

from datetime import datetime, timezone
from zoneinfo import ZoneInfo
my_datetime = datetime(2021, 10, 31, 0, 0, tzinfo=ZoneInfo('Africa/Johannesburg'))
my_datetime.astimezone(timezone.utc)
datetime.datetime(2021, 10, 30, 22, 0, tzinfo=datetime.timezone.utc)

As you can see there is a 2hr diff between Africa/Johannesburg and UTC

like image 37
run_the_race Avatar answered Oct 20 '25 02:10

run_the_race



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!