简体   繁体   English

我从当地时间转换为UTC有什么问题

[英]What is wrong with my conversion from local time to UTC

According to timeanddate.com, currently Chicago is 5 hours behind UTC. 根据timeanddate.com,目前芝加哥比UTC晚了5个小时。 However, my Python app thinks differently: 但是,我的Python应用程序有不同的看法

import datetime
import pytz

    local_tz = pytz.timezone('America/Chicago')
    local_time = datetime.datetime(2015, 8, 6, 0, 0, tzinfo=local_tz)
    utc_time = local_time.astimezone(pytz.utc)
    print(local_time)
    print(utc_time)

2015-08-06 00:00:00-05:51
2015-08-06 05:51:00+00:00

I am getting the same results with both 'America/Chicago' and 'US/Central'. 我在“美国/芝加哥”和“美国/中部”获得了相同的结果。 Why is the offset -05:51 instead of -05:00? 为什么偏移-05:51而不是-05:00?

pytz timezone objects need to be initialized with a specific time before they're used, and creating a datetime with a tzinfo= parameter does not allow for that. pytz时区对象需要在使用之前使用特定时间进行初始化,并且使用tzinfo=参数创建datetime时间不允许这样做。 You have to use the localize method of the pytz object to add the timezone to the datetime . 您必须使用pytz对象的localize方法将时区添加到datetime

>>> local_tz = pytz.timezone('America/Chicago')
>>> local_time = local_tz.localize(datetime.datetime(2015, 8, 6, 0, 0))
>>> print local_time
2015-08-06 00:00:00-05:00
>>> utc_time = local_time.astimezone(pytz.utc)
>>> print utc_time
2015-08-06 05:00:00+00:00

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM