【问题标题】:Different behaviour of datetime.astimezone on Python 3.9.5 and Python 3.9.6Python 3.9.5 和 Python 3.9.6 上 datetime.astimezone 的不同行为
【发布时间】:2023-03-10 09:58:01
【问题描述】:

Python 3.9.6 上,这可以按预期工作:

import datetime

A = datetime.datetime(2021,1,1)

A.astimezone(datetime.timezone.utc)
    >> datetime.datetime(2021, 1, 1, 0, 0, tzinfo=datetime.timezone.utc)

但在 Python 3.9.5 上,我得到:

import datetime

A = datetime.datetime(2021,1,1)

A.astimezone(datetime.timezone.utc)
    >> datetime.datetime(2020, 12, 31, 23, 0, tzinfo=datetime.timezone.utc)

为什么会有这种行为?我只想通过保留原始日期时间数据来将 utc 感知 tzone 添加到天真的日期时间,如 3.9.6 中所示。

【问题讨论】:

  • 两个 Python 版本安装的库版本是否存在差异?
  • zoneinfo module相关的3.9.6可能有一些变化。
  • @sophros 不,pytz 在两者上都有相同的版本(2021.1)
  • 你为什么首先使用 pytz? Python 3.9 不再需要它。你有zoneinfo。对于 UTC,您甚至在 datetime 模块中有 timezone.utc
  • @MrFuppes 好的,已更新

标签: python python-3.x datetime pytz


【解决方案1】:

我已经在 Windows 上进行了测试,其中提到了 Python 版本。我的机器的时区设置是“欧洲/柏林”,所以天真的日期时间 datetime(2021,1,1) 比 UTC 早一小时。因此,转换应该给出 2020-12-31T23:00:00,正如您在 the docs 中看到的那样:

如果提供,tz 必须是 tzinfo 子类的实例,并且其 utcoffset() 和 dst() 方法不得返回 None。 如果 self 是幼稚的,则假定它代表系统时区中的时间。

输出:

Python 3.9.5 (tags/v3.9.5:0a7dcbd, May  3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime, timezone
>>> A = datetime(2021,1,1)
>>> A.astimezone(timezone.utc)
datetime.datetime(2020, 12, 31, 23, 0, tzinfo=datetime.timezone.utc)
Python 3.9.6 (tags/v3.9.6:db3ff76, Jun 28 2021, 15:26:21) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime, timezone
>>> A = datetime(2021,1,1)
>>> A.astimezone(timezone.utc)
datetime.datetime(2020, 12, 31, 23, 0, tzinfo=datetime.timezone.utc)

就目前而言,如果我在同一台机器上为两个 Python 版本使用相同的时区设置运行它,我无法重现所描述的行为。

【讨论】:

    猜你喜欢
    • 2013-04-01
    • 1970-01-01
    • 2021-12-16
    • 2021-09-22
    • 2021-09-27
    • 2021-09-18
    • 2021-08-21
    • 2021-08-15
    • 1970-01-01
    相关资源
    最近更新 更多