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

我确信我以前做过这个,但找不到它,所以希望将来能帮助我(和其他人)做到这一点。

澄清:例如,如果我的本地时区(+10)是2008-09-17 14:02:00,我希望生成一个具有等效UTC时间的字符串:2008-09-17 04:02:00。

此外,从http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/请注意,一般来说,这是不可能的,因为DST和其他问题没有从本地时间到UTC时间的唯一转换。


当前回答

import time

import datetime

def Local2UTC(LocalTime):

    EpochSecond = time.mktime(LocalTime.timetuple())
    utcTime = datetime.datetime.utcfromtimestamp(EpochSecond)

    return utcTime

>>> LocalTime = datetime.datetime.now()

>>> UTCTime = Local2UTC(LocalTime)

>>> LocalTime.ctime()

'Thu Feb  3 22:33:46 2011'

>>> UTCTime.ctime()

'Fri Feb  4 05:33:46 2011'

其他回答

谢谢@rofly,从字符串到字符串的完整转换如下:

import time
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.mktime 本地时间元组——自epoch以来>秒(始终是本地时间)

time.gmtime seconds since epoch——UTC中的>元组

and

calendar.timegm tuple in UTC——> seconds since epoch

time.localtime 自epoch ->元组在本地时区的秒数

下面是一些常见的Python时间转换的总结。

有些方法以秒为单位,用(s)标记。可以使用显式公式,如ts = (d - epoch) / unit代替(感谢jfs)。

struct_time (UTC) → POSIX (s):calendar.timegm(struct_time) Naïve datetime (local) → POSIX (s):calendar.timegm(stz.localize(dt, is_dst=None).utctimetuple())(exception during DST transitions, see comment from jfs) Naïve datetime (UTC) → POSIX (s):calendar.timegm(dt.utctimetuple()) Aware datetime → POSIX (s):calendar.timegm(dt.utctimetuple()) POSIX → struct_time (UTC, s):time.gmtime(t)(see comment from jfs) Naïve datetime (local) → struct_time (UTC, s):stz.localize(dt, is_dst=None).utctimetuple()(exception during DST transitions, see comment from jfs) Naïve datetime (UTC) → struct_time (UTC, s):dt.utctimetuple() Aware datetime → struct_time (UTC, s):dt.utctimetuple() POSIX → Naïve datetime (local):datetime.fromtimestamp(t, None)(may fail in certain conditions, see comment from jfs below) struct_time (UTC) → Naïve datetime (local, s):datetime.datetime(struct_time[:6], tzinfo=UTC).astimezone(tz).replace(tzinfo=None)(can't represent leap seconds, see comment from jfs) Naïve datetime (UTC) → Naïve datetime (local):dt.replace(tzinfo=UTC).astimezone(tz).replace(tzinfo=None) Aware datetime → Naïve datetime (local):dt.astimezone(tz).replace(tzinfo=None) POSIX → Naïve datetime (UTC):datetime.utcfromtimestamp(t) struct_time (UTC) → Naïve datetime (UTC, s):datetime.datetime(*struct_time[:6])(can't represent leap seconds, see comment from jfs) Naïve datetime (local) → Naïve datetime (UTC):stz.localize(dt, is_dst=None).astimezone(UTC).replace(tzinfo=None)(exception during DST transitions, see comment from jfs) Aware datetime → Naïve datetime (UTC):dt.astimezone(UTC).replace(tzinfo=None) POSIX → Aware datetime:datetime.fromtimestamp(t, tz)(may fail for non-pytz timezones) struct_time (UTC) → Aware datetime (s):datetime.datetime(struct_time[:6], tzinfo=UTC).astimezone(tz)(can't represent leap seconds, see comment from jfs) Naïve datetime (local) → Aware datetime:stz.localize(dt, is_dst=None)(exception during DST transitions, see comment from jfs) Naïve datetime (UTC) → Aware datetime:dt.replace(tzinfo=UTC)

来源:taaviburns.ca

你可以用:

>>> from time import strftime, gmtime, localtime
>>> strftime('%H:%M:%S', gmtime()) #UTC time
>>> strftime('%H:%M:%S', localtime()) # localtime
def local_to_utc(t):
    secs = time.mktime(t)
    return time.gmtime(secs)

def utc_to_local(t):
    secs = calendar.timegm(t)
    return time.localtime(secs)

来源:http://feihonghsu.blogspot.com/2008/02/converting-from-local-time-to-utc.html

来自bd808的示例用法:如果您的源是一个datetime。Datetime对象t,调用as:

local_to_utc(t.timetuple())

注意:从2020年开始,你不应该使用.utcnow()或.utcfromtimestamp(xxx)。当您已经迁移到python3时,您应该使用时区感知的datetime对象。

>>> from datetime import timezone
>>> 
>>> # alternative to '.utcnow()'
>>> dt_now = datetime.datetime.now(datetime.timezone.utc)
>>>
>>> # alternative to '.utcfromtimestamp()'
>>> dt_ts = datetime.fromtimestamp(1571595618.0, tz=timezone.utc)

详情见:https://blog.ganssle.io/articles/2019/11/utcnow.html

最初的答案(2010年):

datetime模块的utcnow()函数可用于获取当前UTC时间。

>>> import datetime
>>> utc_datetime = datetime.datetime.utcnow()
>>> utc_datetime.strftime("%Y-%m-%d %H:%M:%S")
'2010-02-01 06:59:19'

正如Tom上面提到的链接:http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/所说:

UTC是一个没有夏令时的时区,但仍然是一个时区 过去没有配置更改。 始终以UTC度量和存储时间。 如果你需要记录时间是在哪里花费的,分开存储。 不要保存本地时间+时区信息!

注意—如果您的任何数据位于使用夏令时的地区,请使用pytz并查看John Millikin的答案。

如果你想从一个给定的字符串中获得UTC时间,并且你足够幸运地处于世界上一个不使用夏令时的地区,或者你的数据只与UTC时间有偏移,而没有应用夏令时:

——>使用当地时间作为偏移值的基础:

>>> # Obtain the UTC Offset for the current system:
>>> UTC_OFFSET_TIMEDELTA = datetime.datetime.utcnow() - datetime.datetime.now()
>>> local_datetime = datetime.datetime.strptime("2008-09-17 14:04:00", "%Y-%m-%d %H:%M:%S")
>>> result_utc_datetime = local_datetime + UTC_OFFSET_TIMEDELTA
>>> result_utc_datetime.strftime("%Y-%m-%d %H:%M:%S")
'2008-09-17 04:04:00'

或者,从已知偏移量开始,使用datetime.timedelta():

>>> UTC_OFFSET = 10
>>> result_utc_datetime = local_datetime - datetime.timedelta(hours=UTC_OFFSET)
>>> result_utc_datetime.strftime("%Y-%m-%d %H:%M:%S")
'2008-09-17 04:04:00'

更新:

从python 3.2开始datetime。时区可用。你可以用下面的命令生成一个时区感知的datetime对象:

import datetime

timezone_aware_dt = datetime.datetime.now(datetime.timezone.utc)

如果你已经准备好进行时区转换,请阅读这篇文章:

https://medium.com/@eleroy/10-things-you-need-to-know-about-date-and-time-in-python-with-datetime-pytz-dateutil-timedelta-309bfbafb3f7