I was trying to convert a datetime from one timezone to another. I'm in the process of updating our Python codebase to stop relying on utilities we don't need anymore. In particular, I'm deprecating our use of arrow
and pytz
. In doing so, I noticed some strange behavior from ZoneInfo("UTC")
.
from datetime import datetime, timezone
jan1_in_utc = datetime.fromisoformat('2022-01-01T08:00').replace(tzinfo=ZoneInfo("UTC"))
# This gives datetime.datetime(2022, 1, 1, 8, 0, tzinfo=zoneinfo.ZoneInfo(key='UTC'))
# Let's say I try to convert it to America/Toronto timezone
jan1_in_utc.astimezone(ZoneInfo("America/Toronto"))
# This gives me the SAME date time ?!?!?
# datetime.datetime(2022, 1, 1, 8, 0, tzinfo=zoneinfo.ZoneInfo(key='America/Toronto'))
# However, if I use timezone.utc instead
jan1_in_utc = datetime.fromisoformat('2022-01-01T08:00').replace(tzinfo=timezone.utc)
# This works as expected
jan1_in_utc.astimezone(ZoneInfo("America/Toronto"))
# this correctly calculates a -5 offset
# datetime.datetime(2022, 1, 1, 3, 0, tzinfo=zoneinfo.ZoneInfo(key='America/Toronto'))
I'm not sure what I'm doing wrong. "UTC" is in the list of zoneinfo.available_timezones()
. Using "utc" raises an error.
I also noticed this oddity. Calculating the utcoffset
from the ZoneInfo("UTC")
isn't 0
.
jan1_in_utc = datetime.fromisoformat('2022-01-01T08:00').replace(tzinfo=ZoneInfo("UTC"))
ZoneInfo("UTC").utcoffset(jan1_in_utc)
Where as if I use timezone.utc
, there's no time difference.
jan1_in_utc = datetime.fromisoformat('2022-01-01T08:00').replace(tzinfo=timezone.utc)
timezone.utc.utcoffset(jan1_in_utc)
# This gives datetime.timedelta(0)
Now I'm unsure if I should use ZoneInfo
at all, or if I should still rely on pytz
and arrow
. Any thoughts? Clearly, I'm missing something!
Cannot reproduce. Did you make sure tzdata is installed and up-to-date?
On
I get Toronto time at UTC-5 as expected for both options: