0

I am trying to convert UTC time to CST. But I am not getting the output as expected.

Below is my code:

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

time_from_utc = datetime.datetime.utcfromtimestamp(int(1607020200))
time_from = time_from_utc.astimezone(e)
time_from.strftime(fmt)
time_to_utc = datetime.datetime.utcfromtimestamp(int(1609785000))
time_to = time_to_utc.astimezone(tz=pytz.timezone('US/Central'))
print(time_from_utc)
print(time_from)
print(time_to_utc)
print(time_to)

Here is the output:

(base) ranjeet@casper:~/Desktop$ python3 ext.py 
2020-12-03 18:30:00
2020-12-03 07:00:00-06:00
2021-01-04 18:30:00
2021-01-04 07:00:00-06:00

I was expecting that after conversion, I should get time corresponding to the time of UTC i.e.

2020-12-03 18:30:00
2020-12-03 12:30:00-06:00

since CST is -6 Hours from UTC. Any help is appreciated.

Ranjeet SIngh
  • 381
  • 5
  • 15
  • 1
    I had a look at this and running your code on my local laptop and online in a repl and i get the output you expect. Have you tried running your code else where. Maybe its a local issue with the machine where the code is running. – Chris Doyle Jan 04 '21 at 12:43
  • I am trying to convert DateTime with timezone. Like naive date object to timezone aware. But I am failing. I tried it on different machines as well, with different venv but I am getting the same result. – Ranjeet SIngh Jan 04 '21 at 12:59
  • Note: [Stop using utcnow and utcfromtimestamp](https://blog.ganssle.io/articles/2019/11/utcnow.html). – FObersteiner Jan 04 '21 at 14:53

1 Answers1

2

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.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72