在Python中如何将本地时间转换为UTC? [英] How do I convert local time to UTC in Python?
问题描述
如何将本地时间的日期时间字符串转换为UTC时间的字符串?
How do I convert a datetime string in local time to a string in UTC time?
I 我确定我以前做过,但是找不到,而且将来希望帮助我(和其他人)这样做。
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
c $ c>),我想生成一个字符串,具有等价的 UTC
time: 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.strptime
string - > tuple(没有时区应用,所以匹配字符串)
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
秒,因为epoch - > tuple在UTC
time.gmtime
seconds since epoch --> tuple in UTC
和
日历.timegm
tuple in UTC - > epoch
calendar.timegm
tuple in UTC --> seconds since epoch
time.localtime
秒从epoch - > tuple在本地时区
time.localtime
seconds since epoch --> tuple in local timezone
这篇关于在Python中如何将本地时间转换为UTC?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!