【问题标题】:Converting tz naive datetime to tz aware jumps from 0 minutes to 58将 tz naive datetime 转换为 tz 感知从 0 分钟到 58 分钟
【发布时间】:2020-05-01 17:38:22
【问题描述】:

当我将不知道的 datetime 转换为有意识时,它会做一件奇怪的事情。它增加了 58 分钟。

_datetime = datetime.combine(_date,_time)
print(_datetime)
datetime_tz = _datetime.replace(tzinfo='Europe/Bratislava')
print(_datetime_tz)

2020-02-02 12:45:00
2020-02-02 12:45:00+00:58

你知道为什么以及如何让它发挥作用吗?

【问题讨论】:

  • 那是因为你使用的是replace而不是pytz的localize

标签: python timezone python-datetime pytz


【解决方案1】:

要正确使用来自pytz 的时区对象,您必须使用localize 函数。

>>> import pytz
>>> tz = pytz.timezone('Europe/Bratislava')
>>> _datetime = datetime.combine(_date,_time)
>>> print(_datetime)
2020-02-02 12:45:00
>>> _datetime_tz = tz.localize(_datetime)
>>> print(_datetime_tz)
2020-02-02 12:45:00+01:00

如果您不这样做,则时区对象处于无效状态,因为它没有机会针对日期进行调整。

【讨论】:

    猜你喜欢
    • 2014-12-30
    • 1970-01-01
    • 2020-05-03
    • 2015-05-18
    • 1970-01-01
    • 1970-01-01
    • 2014-12-01
    • 2015-07-20
    • 2022-11-14
    相关资源
    最近更新 更多