如何将本地时间字符串转换为 UTC? [英] How to convert local time string to UTC?
问题描述
如何将日期时间本地时间字符串转换为UTC时间字符串?
How do I convert a datetime string in local time to a string in UTC time?
我确定我以前做过这个,但找不到它,所以希望将来能帮助我(和其他人)做到这一点.
I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future.
澄清:例如,如果我在本地时区 (+10
) 中有 2008-09-17 14:02:00
,我想生成一个具有等效 UTC
时间的字符串:2008-09-17 04:02:00
.
Clarification: For example, if I have 2008-09-17 14:02:00
in my local timezone (+10
), I'd like to generate a string with the equivalent UTC
time: 2008-09-17 04:02:00
.
另外,来自 http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/,请注意,通常这是不可能的,因为 DST 和其他问题没有从本地时间到 UTC 时间的唯一转换.
Also, from http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/, note that in general this isn't possible as with DST and other issues there is no unique conversion from local time to UTC time.
推荐答案
感谢@rofly,字符串到字符串的完整转换如下:
Thanks @rofly, the full conversion from string to string is as follows:
time.strftime("%Y-%m-%d %H:%M:%S",
time.gmtime(time.mktime(time.strptime("2008-09-17 14:04:00",
"%Y-%m-%d %H:%M:%S"))))
我对time
/calendar
函数的总结:
time.strptime
字符串 --> 元组(没有应用时区,所以匹配字符串)
time.strptime
string --> tuple (no timezone applied, so matches string)
time.mktime
本地时间元组 --> 自纪元以来的秒数(始终为本地时间)
time.mktime
local time tuple --> seconds since epoch (always local time)
time.gmtime
自纪元以来的秒数 --> UTC 中的元组
time.gmtime
seconds since epoch --> tuple in UTC
和
calendar.timegm
UTC 中的元组 --> 自纪元以来的秒数
calendar.timegm
tuple in UTC --> seconds since epoch
time.localtime
自纪元以来的秒数 --> 本地时区中的元组
time.localtime
seconds since epoch --> tuple in local timezone
这篇关于如何将本地时间字符串转换为 UTC?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!