【问题标题】:Python seeming to incorrectly handle time zone conversionsPython 似乎无法正确处理时区转换
【发布时间】:2015-10-14 14:33:05
【问题描述】:

我对我正在编写的用于转换日期和时间的 python 程序中的以下行为感到困惑。我将原始“挂钟时间”中的数据作为新西兰标准时间,并希望将其转换为始终为 UTC+12(或 pytz 中提供的 GMT+12)。

问题是当我运行程序时,它给出的结果似乎不正确。示例输出如下所示。当输入 24/07/2015 08:00 小时(2015 年 7 月 24 日上午 8 点)的日期,定义为“太平洋/奥克兰”,然后转换为 GMT+12 时,它似乎给出了提前一天的错误结果。我不确定为什么会这样,因为如果我对时区转换的理解是正确的,那么时间应该完全相同。

有人能指出我在这里做错了什么吗?

程序输出:

Pacific/Auckland
24/07/2015 08:00
23/07/2015 08:00

“最小工作示例”源代码:

#!/usr/bin/env python

import time
import pytz
import datetime

def main():

    time_zone = 'Pacific/Auckland'
    print(time_zone)

    local = pytz.timezone(time_zone)

    time_str = '24/07/2015 08:00'
    print(time_str)

    t = time.strptime(time_str, '%d/%m/%Y %H:%M')
    t_datetime = datetime.datetime.fromtimestamp(time.mktime(t))

    local_dt = local.localize(t_datetime)

    ds2 = local_dt.astimezone(pytz.timezone('Etc/GMT+12')).strftime('%d/%m/%Y %H:%M')

    print(ds2)


if __name__ == '__main__':
    # Parse the system arguments and get the busbar and input directory.
    main()

##### END OF FILE #####

【问题讨论】:

  • 这是一个实现问题;它属于 Stack Overflow,而不是这里。

标签: python time timezone


【解决方案1】:

POSIX style timezones ('Etc/GMT+h') have the opposite sign。您正在从 +1200 转换为 -1200 总共 24 小时休息,这就是为什么您得到相同的时间但错误的日期。

#!/usr/bin/env python
from datetime import datetime
import pytz # $ pip install pytz

naive = datetime.strptime('24/07/2015 08:00', '%d/%m/%Y %H:%M')
aware = pytz.timezone('Pacific/Auckland').localize(naive, is_dst=None)
print(aware)
utc_dt = aware.astimezone(pytz.utc)
print(utc_dt)
# +1200
print(utc_dt.astimezone(pytz.timezone('Etc/GMT-12')))

输出

2015-07-24 08:00:00+12:00
2015-07-23 20:00:00+00:00
2015-07-24 08:00:00+12:00

【讨论】:

  • 谢谢。我看到我被 12 小时的时差所吸引。 pytz中没有像Etc/UTC+12这样的时区有什么原因吗?
  • @bjem:与 posix 风格的时区本身有足够的混淆。目前尚不清楚为什么需要一个固定的非零偏移量。使用命名时区,例如太平洋/奥克兰或 UTC。
  • Pacific/Auckland 不好,因为它有夏令时,我不希望在我的数据库中。 UTC+12 更适合此目的,因为它与新西兰的冬季时间相匹配,并且在夏季落后一个小时,这比 UTC 更容易混淆,通常落后 12 小时,夏季落后 13 小时。
  • 使用UTC,以免与本地时间混淆
猜你喜欢
  • 1970-01-01
  • 2017-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-22
  • 1970-01-01
  • 2010-11-27
  • 2015-12-02
相关资源
最近更新 更多