首页 > 解决方案 > 为什么在使用 datetime.max 时会出现 ValueError?

问题描述

为什么我ValueError在这个例子中得到一个?

>>> import datetime
>>> datetime.datetime.max.timestamp()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: year 10000 is out of range

我正在使用 Python 3.8.3。

标签: pythonpython-datetimepython-3.8

解决方案


我得到了一个OSError: [Errno 22] Invalid argument使用 Python 3.6。这就是文档所说的:

笔记

没有直接从表示 UTC 时间的简单日期时间实例获取 POSIX 时间戳的方法。如果您的应用程序使用此约定并且您的系统时区未设置为 UTC,您可以通过提供 tzinfo=timezone.utc 来获取 POSIX 时间戳:

timestamp = dt.replace(tzinfo=timezone.utc).timestamp()

或通过直接计算时间戳:

timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)

所以当我尝试时:

>>> import datetime
>>> datetime.datetime.max.replace(tzinfo=datetime.timezone.utc).timestamp()
253402300800.0

推荐阅读