converting time from UTC to CST

the problem is that

time_from_utc = datetime.datetime.utcfromtimestamp(int(1607020200))

gives you a naive datetime object – which Python treats as local time by default. Then, in

time_from = time_from_utc.astimezone(e)

things go wrong since time_from_utc is treated as local time. Instead, set UTC explicitly when calling fromtimestamp:

from datetime import datetime, timezone
import pytz

fmt = '%Y-%m-%d %H:%M:%S %Z%z'
e = pytz.timezone('US/Central')

time_from_utc = datetime.fromtimestamp(1607020200, tz=timezone.utc)
time_from = time_from_utc.astimezone(e)
time_from.strftime(fmt)
time_to_utc = datetime.fromtimestamp(1609785000, tz=timezone.utc)
time_to = time_to_utc.astimezone(tz=pytz.timezone('US/Central'))

  • which will give you
2020-12-03 18:30:00+00:00
2020-12-03 12:30:00-06:00
2021-01-04 18:30:00+00:00
2021-01-04 12:30:00-06:00

Final Remarks: with Python 3.9, you have zoneinfo, so you don’t need a third party library for handling of time zones. Example usage.

Leave a Comment