python - 为什么在使用 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。
解决方案
我得到了一个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
推荐阅读
- typescript - tsc --build 多次输出相同的错误
- flutter - 如何在管理状态(GetX)的同时使用动画?
- c# - 在 C# 中,如何使用反射添加 FluentValidation 的实例?
- macos - vscode 的扩展指南是开源的吗?
- sql - 如何在一个语句中使用单个值 UPSERT 多行?
- math - 百分位数和分位数的区别以及如何计算
- javascript - 完成时自动更新表单字段
- c++ - 可变类成员(元组或其他)的参数包扩展
- nao-robot - 我无法将我的 NAO 机器人与 Wi-Fi 网络连接
- python - 我可以使用曲线拟合的不确定性(Python)绘制误差带吗?