如何将本地时间字符串转换为UTC

如何将本地时间字符串转换为UTC

本文介绍了如何将本地时间字符串转换为UTC?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将本地时间的日期时间字符串转换为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.

澄清:例如,如果我的本地时区为 2008-09-17 14:02:00 +10 ),我想生成一个等效于 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.

此外,来自,请注意,通常这与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

字符串->元组(否应用了时区,因此匹配字符串)

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-27 23:04