如何修复 Python 错误 "AttributeError: 'datetime.datetime' object has no attribute 'timestamp'"
问题:
你想在 Python 中使用类似这样的代码将 datetime 对象转换为 unix 时间戳(int 或 float:自 1970-1-1 00:00:00 以来的秒数)
unix_timestamp_example.py
from datetime import datetime
timestamp = datetime.now().timestamp()但你看到类似这样的错误消息:
timestamp_traceback.txt
Traceback (most recent call last):
File "unix-timestamp.py", line 2, in <module>
timestamp = datetime.now().timestamp()
AttributeError: 'datetime.datetime' object has no attribute 'timestamp'解决方案
你正在使用 Python 2.x 运行代码,它不支持 datetime.timestamp() - 在大多数情况下,解决此问题的最简单方法是使用 Python 3,例如:
run_python3.sh
python3 unix-timestamp.py如果由于不兼容等原因不可能,请使用此代码片段,它与 Python 2 和 Python 3 兼容:
unix_timestamp_compat.py
from datetime import datetime
import time
dt = datetime.now()
timestamp = time.mktime(dt.timetuple()) + dt.microsecond/1e6Check out similar posts by category:
Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow