提问人:Ames ISU 提问时间:9/7/2023 最后编辑:FObersteinerAmes ISU 更新时间:9/7/2023 访问量:49
如何在python中将带有时区信息的时间戳转换为UTC时间
How can I convert the time stamp with timezone info to utc time in python
问:
我有这样的时间字符串“2023-09-06T22:02:44-07:00”,是通过调用获取的
datetime.now().astimezone().isoformat(timespec='seconds')
我的问题是如何将时间字符串“2023-09-06T22:02:44-07:00”转换为UTC时间?基本上如何转换它,使 -07:00 成为 +00:00?
答:
1赞
blhsing
9/7/2023
#1
您可以先使用该方法将时间戳字符串转换为对象,然后调用该方法将其转换为 UTC 时区,并将转换后的时间戳以 ISO 格式输出:fromisoformat
datetime
astimezone(timezone.utc)
isoformat
from datetime import datetime, timezone
t = "2023-09-06T22:02:44-07:00"
print(datetime.fromisoformat(t).astimezone(timezone.utc).isoformat(timespec='seconds'))
这将输出:
2023-09-07T05:02:44+00:00
评论
0赞
Ames ISU
9/8/2023
一个后续问题,如果我想获取像“2023-09-06T22:02:44-PDT”这样的时间字符串(而不是最后的 07:00)并将其转换为 UTC,有什么快速方法可以做到这一点吗?
0赞
blhsing
9/8/2023
哎呀,我想我误会了你的后续问题。如果您真的想转换为UTC时间戳,您可以尝试: stackoverflow.com/a/62714463/6890912"2023-09-06T22:02:44-PDT"
评论