将时间从 UTC 转换为 CST

时间:2021-01-04 12:26:06

标签: python-3.x timezone python-datetime strftime pytz

我正在尝试将 UTC 时间转换为 CST。但我没有得到预期的输出。

下面是我的代码:

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)

输出如下:

(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

我期待转换后,我应该得到与UTC时间相对应的时间,即

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

因为 CST 与 UTC 时间相差 -6 小时。 任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:2)

问题

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

为您提供一个简单的 datetime 对象 - Python 默认将其视为本地时间。然后,在

time_from = time_from_utc.astimezone(e)

出现问题,因为 time_from_utc 被视为本地时间。相反,在调用 fromtimestamp 时显式设置 UTC:

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'))
  • 这会给你
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

最后说明:在 Python 3.9 中,您有 zoneinfo,因此您不需要第三方库来处理时区。 Example usage

相关问题