A careful reading of the pytz
documentation yields this condensed information:
- This library only supports two ways of building a localized time. The first is to use the
localize()
method provided by the pytz library. This is used to localize a naive datetime (datetime with no timezone information). The second way of building a localized time is by converting an existing localized time using the standard astimezone()
method.
- Unfortunately using the tzinfo argument of the standard datetime constructors ‘’does not work’’ with pytz for many timezones. It is safe for timezones without daylight saving transitions though, such as UTC. The preferred way of dealing with times is to always work in UTC, converting to localtime only when generating output to be read by humans.
This suggests that you should be converting from UTC
to America/New_York
, not the other way around, using astimezone
:
from pytz import timezone
from datetime import datetime
utc = timezone('UTC')
nyc = timezone('America/New_York')
dt_utc = datetime(2022, 10, 10, 17, 30, tzinfo=utc)
print(dt_utc)
dt_nyc = dt_utc.astimezone(nyc)
print(dt_nyc)
print('-------------------------')
dt_utc = utc.localize(datetime(2022, 10, 10, 17, 30))
print(dt_utc)
dt_nyc = nyc.localize(datetime(2022, 10, 10, 13, 30))
print(dt_nyc)
print(dt_utc == dt_nyc)
Prints:
2022-10-10 17:30:00+00:00
2022-10-10 13:30:00-04:00
-------------------------
2022-10-10 17:30:00+00:00
2022-10-10 13:30:00-04:00
True