【问题标题】:Datetime timezone conversion adding minute instead of hour offset [duplicate]日期时间时区转换添加分钟而不是小时偏移量[重复]
【发布时间】:2020-08-30 21:17:18
【问题描述】:

我似乎遇到了一个奇怪的问题。也许这是 Python 中的一个错误,但如果是,我会感到惊讶。

我正在尝试通过第一个时区信息将天真的日期时间转换为 UTC:

import datetime
from pytz import timezone

naive_datetime = datetime.datetime.now()
local_datetime = naive_datetime.replace(tzinfo=timezone('Europe/London'))
utc_datetime = local_datetime.astimezone(timezone('UTC'))
print("Naive datetime:", naive_datetime)
print("Local datetime:", local_datetime)
print("UTC datetime:  ", utc_datetime)

这是输出:

Naive datetime: 2020-05-14 11:46:44.637956
Local datetime: 2020-05-14 11:46:44.637956-00:01
UTC datetime:   2020-05-14 11:47:44.637956+00:00

请注意,添加“欧洲/伦敦”的“本地时区”会增加 -1 分钟的偏移量,而不是我预期的 +1 小时,导致原始时间的“UTC”时间 +1 分钟而不是 -1 小时.

为什么要添加一分钟偏移量,我如何让它达到我的预期?

【问题讨论】:

    标签: python datetime timezone


    【解决方案1】:

    不要replace() 时区,localize() 日期时间对象:

    import datetime
    from pytz import timezone
    
    # call now() with a tz
    local_datetime = datetime.datetime.now(tz=timezone('Europe/London'))
    
    # or localize
    naive_datetime = datetime.datetime.now()
    tz = timezone('Europe/London')
    local_datetime = tz.localize(naive_datetime)
    # datetime.datetime(2020, 5, 14, 13, 6, 2, 512100, tzinfo=<DstTzInfo 'Europe/London' BST+1:00:00 DST>)
    
    # now you can use astimezone to change the tz:
    utc_datetime = local_datetime.astimezone(timezone('UTC'))
    # datetime.datetime(2020, 5, 14, 12, 6, 2, 512100, tzinfo=<UTC>)
    

    注意:如果您在具有 DST 的时区之间进行更改,您可能还需要normalize(),请参阅例如here.

    【讨论】:

    • 谢谢。也很高兴了解 normalize()。我找到了将 replace() 行更改为:python local_datetime = naive_datetime.astimezone(timezone('Europe/London')) 的解决方案,但我认为您的 localize() 解决方案更清楚地了解代码在做什么。
    • @OliverP:很高兴我能帮上忙。请注意,在幼稚的 datetime 对象上调用 astimezone 将使 Python 假定 datetime 对象属于操作系统的时区。
    猜你喜欢
    • 2012-03-22
    • 1970-01-01
    • 1970-01-01
    • 2018-02-20
    • 2016-04-29
    • 1970-01-01
    • 2017-01-16
    • 1970-01-01
    • 2021-12-27
    相关资源
    最近更新 更多