如何在 Python 中将 datetime 转换为 UTC 时间戳?


你可以使用 datetime 模块将 datetime 转换为 UTC 时间戳 Python。如果你已在 UTC 中获取了 datetime 对象,则可以使用 timestamp() 获取 UTC 时间戳。此函数返回该 datetime 对象距历元 epoch 的时间。如果你在本地时区获取了 datetime 对象,请首先替换时区信息,然后获取时间。 

示例

from datetime import timezone
dt = datetime(2015, 10, 19)
timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
print(timestamp)

输出

这会生成如下输出 −

1445212800.0

如果你的 Python 版本为 2,那么可以使用 total_seconds() 函数获取距历元 epoch 的总秒数。如果你想除去时间戳,则可以首先减去 1970 年 1 月 1 日的时间。 

示例

from datetime import timezone
dt = datetime(2015, 10, 19)
timestamp = (dt - datetime(1970, 1, 1)).total_seconds()
print(timestamp)

输出

这会生成如下输出 −

1445212800.0

更新日期:2023 年 8 月 26 日

3.5 万次浏览

开启您的 职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.