首页 > 解决方案 > 如何在python中将本地时间转换为UTC时间

问题描述

我正在尝试将本地时间转换为 UTC 时间。但得到以下错误。

Error: an integer is required (got type str)

from datetime import datetime

starts_date = '2021-07-30 09:30:00'(timestamp without time zone)

ts = starts_date
x = datetime.utcfromtimestamp(ts)
x_ts = x.timestamp()

标签: pythonpython-3.xutcpython-datetime

解决方案


这是一个将(现在)的时间戳转换为 UTC 时间戳的工作示例。

from datetime import datetime as dt

# Create a timestamp object for now.
ts = dt.timestamp(dt.now())

# Convert now to a UTC timestamp.
dt.utcfromtimestamp(ts).timestamp()

>>> 1627637013.657752

推荐阅读