如何在 Python 2 中将 datetime 转换为 time float(unix 时间戳)
使用此代码片段在 Python 2.x 中将 datetime.datetime 对象转换为 float(类似于 time.time() 返回的值):
datetime_to_timestamp_example.py
from datetime import datetime
import time
dt = datetime.now()
timestamp = time.mktime(dt.timetuple()) + dt.microsecond/1e6运行此代码后,timestamp 将例如为 1563812373.1795。
或使用此函数:
datetime_to_timestamp_func.py
from datetime import datetime
import time
def datetime_to_timestamp(dt):
return time.mktime(dt.timetuple()) + dt.microsecond/1e6在 Python 3 中,你可以简单地使用
datetime_to_timestamp_py3.py
dt.timestamp()但这在 Python 2 中不受支持。
Check 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