繁体   English   中英

如何在python中将当地时间转换为UTC时间

[英]How to convert the local time into utc time in python

我正在尝试将本地时间转换为 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()

确保 datetime 正确导入为from datetime import datetime 可能有点混乱,但方法utcfromtimestamp属于datetime.datetime而不是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

datetime.utcfromtimestamp()采用一个整数,表示自 1970 年 1 月 1 日以来经过的秒数。这意味着

from datetime import datetime as dt
print(dt.utcfromtimestamp(0))

你得到

1970-01-01 00:00:00

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM