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

问题描述 投票:264回答:18

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

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

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

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

python datetime utc localtime
18个回答
243
投票

首先,将字符串解析为一个天真的日期时间对象。这是datetime.datetime的一个实例,没有附加时区信息。有关解析日期字符串的信息,请参阅datetime.strptime的文档。

使用pytz模块,该模块附带完整的时区列表+ UTC。弄清楚当地时区是什么,从中构建时区对象,并操纵它并将其附加到天真的日期时间。

最后,使用datetime.astimezone()方法将datetime转换为UTC。

源代码,使用当地时区“America / Los_Angeles”,字符串“2001-2-3 10:11:12”:

import pytz, datetime
local = pytz.timezone ("America/Los_Angeles")
naive = datetime.datetime.strptime ("2001-2-3 10:11:12", "%Y-%m-%d %H:%M:%S")
local_dt = local.localize(naive, is_dst=None)
utc_dt = local_dt.astimezone(pytz.utc)

从那里,您可以使用strftime()方法根据需要格式化UTC日期时间:

utc_dt.strftime ("%Y-%m-%d %H:%M:%S")

5
投票

如果您更喜欢datetime.datetime:

dt = datetime.strptime("2008-09-17 14:04:00","%Y-%m-%d %H:%M:%S")
utc_struct_time = time.gmtime(time.mktime(dt.timetuple()))
utc_dt = datetime.fromtimestamp(time.mktime(utc_struct_time))
print dt.strftime("%Y-%m-%d %H:%M:%S")

4
投票

你可以这样做:

>>> from time import strftime, gmtime, localtime
>>> strftime('%H:%M:%S', gmtime()) #UTC time
>>> strftime('%H:%M:%S', localtime()) # localtime

3
投票

怎么样 -

time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(seconds))

如果秒是None然后它将本地时间转换为UTC时间,则将传入的时间转换为UTC。


3
投票

简单

我是这样做的:

>>> utc_delta = datetime.utcnow()-datetime.now()
>>> utc_time = datetime(2008, 9, 17, 14, 2, 0) + utc_delta
>>> print(utc_time)
2008-09-17 19:01:59.999996

花哨的实施

如果你想获得幻想,你可以把它变成一个仿函数:

class to_utc():
    utc_delta = datetime.utcnow() - datetime.now()

    def __call__(cls, t):
        return t + cls.utc_delta

结果:

>>> utc_converter = to_utc()
>>> print(utc_converter(datetime(2008, 9, 17, 14, 2, 0)))
2008-09-17 19:01:59.999996

2
投票

为了避免日光节约等

上述答案都没有对我有所帮助。以下代码适用于GMT。

def get_utc_from_local(date_time, local_tz=None):
    assert date_time.__class__.__name__ == 'datetime'
    if local_tz is None:
        local_tz = pytz.timezone(settings.TIME_ZONE) # Django eg, "Europe/London"
    local_time = local_tz.normalize(local_tz.localize(date_time))
    return local_time.astimezone(pytz.utc)

import pytz
from datetime import datetime

summer_11_am = datetime(2011, 7, 1, 11)
get_utc_from_local(summer_11_am)
>>>datetime.datetime(2011, 7, 1, 10, 0, tzinfo=<UTC>)

winter_11_am = datetime(2011, 11, 11, 11)
get_utc_from_local(winter_11_am)
>>>datetime.datetime(2011, 11, 11, 11, 0, tzinfo=<UTC>)

2
投票

使用http://crsmithdev.com/arrow/

arrowObj = arrow.Arrow.strptime('2017-02-20 10:00:00', '%Y-%m-%d %H:%M:%S' , 'US/Eastern')

arrowObj.to('UTC') or arrowObj.to('local') 

这个图书馆让生活更轻松:)


0
投票

在python3中:

pip install python-dateutil

from dateutil.parser import tz

mydt.astimezone(tz.gettz('UTC')).replace(tzinfo=None) 

0
投票

我找到了另一个问题here的最佳答案。它只使用python内置库,不需要你输入你的本地时区(在我的情况下是一个要求)

import time
import calendar

local_time = time.strptime("2018-12-13T09:32:00.000", "%Y-%m-%dT%H:%M:%S.%f")
local_seconds = time.mktime(local_time)
utc_time = time.gmtime(local_seconds)

我在这里重新发布答案,因为这个问题会在谷歌中弹出而不是链接的问题,具体取决于搜索关键字。


-1
投票

在这种情况下... pytz是最好的lib

import pytz
utc = pytz.utc
yourdate = datetime.datetime.now()
yourdateutc = yourdate.astimezone(utc).replace(tzinfo=None)

122
投票

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'

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

UTC是一个没有夏令时的时区,过去仍然没有配置更改的时区。

始终以UTC格式测量和存储时间。

如果您需要记录拍摄时间,请单独存储。不要存储当地时间+时区信息!

注意 - 如果您的任何数据位于使用DST的区域,请使用pytz并查看John Millikin的答案。

如果您想从给定字符串中获取UTC时间,并且您有幸在世界上不使用DST的区域中,或者您的数据仅在未应用DST的情况下偏离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.timezone可用。您可以使用以下命令生成时区感知日期时间对象:

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


61
投票

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

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 string - > tuple(未应用时区,因此匹配字符串)

time.mktime 本地时间元组 - >自纪元以来的秒数(总是当地时间)

time.gmtime 自纪元以来的秒数 - > UTC中的元组

calendar.timegm UTC中的元组 - >自纪元以来的秒数

time.localtime 自纪元以来的秒数 - >当地时区的元组


34
投票

以下是常见Python时间转换的摘要。

有些方法会丢弃几秒钟,并标有(s)。可以使用诸如ts = (d - epoch) / unit之类的显式公式(感谢jfs)。

  • struct_time(UTC)→POSIX: calendar.timegm(struct_time)
  • 天真日期时间(当地)→POSIX: calendar.timegm(stz.localize(dt, is_dst=None).utctimetuple()) (在DST转换期间的异常,请参阅jfs的注释)
  • 天真日期时间(UTC)→POSIX: calendar.timegm(dt.utctimetuple())
  • 意识到日期时间→POSIX: calendar.timegm(dt.utctimetuple())
  • POSIX→struct_time(UTC,s): time.gmtime(t) (参见jfs的评论)
  • 天的日期时间(本地)→struct_time(UTC,s): stz.localize(dt, is_dst=None).utctimetuple() (在DST转换期间的异常,请参阅jfs的注释)
  • 天使日期时间(UTC)→struct_time(UTC,s): dt.utctimetuple()
  • 意识到datetime→struct_time(UTC,s): dt.utctimetuple()
  • POSIX→Naïvedatetime(本地): datetime.fromtimestamp(t, None) (在某些情况下可能会失败,请参阅以下jfs的评论)
  • struct_time(UTC)→Naïvedatetime(local,s): datetime.datetime(struct_time[:6], tzinfo=UTC).astimezone(tz).replace(tzinfo=None) (不能代表闰秒,请参阅jfs的评论)
  • 天用日期时间(UTC)→天用日期时间(本地): dt.replace(tzinfo=UTC).astimezone(tz).replace(tzinfo=None)
  • 意识到日期时间→天使日期时间(本地): dt.astimezone(tz).replace(tzinfo=None)
  • POSIX→Naïvedatetime(UTC): datetime.utcfromtimestamp(t)
  • struct_time(UTC)→Naïvedatetime(UTC,s): datetime.datetime(*struct_time[:6]) (不能代表闰秒,请参阅jfs的评论)
  • 天真日期时间(本地)→天真日期时间(UTC): stz.localize(dt, is_dst=None).astimezone(UTC).replace(tzinfo=None) (在DST转换期间的异常,请参阅jfs的注释)
  • 意识到日期时间→天使日期时间(UTC): dt.astimezone(UTC).replace(tzinfo=None)
  • POSIX→感知日期时间: datetime.fromtimestamp(t, tz) (对于非pytz时区可能会失败)
  • struct_time(UTC)→感知日期时间: datetime.datetime(struct_time[:6], tzinfo=UTC).astimezone(tz) (不能代表闰秒,请参阅jfs的评论)
  • 天真日期时间(本地)→意识到日期时间: stz.localize(dt, is_dst=None) (在DST转换期间的异常,请参阅jfs的注释)
  • 天真日期时间(UTC)→意识到日期时间: dt.replace(tzinfo=UTC)

资料来源:taaviburns.ca


25
投票
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,请致电:

local_to_utc(t.timetuple())

19
投票

我和dateutil好运(在其他相关问题上广泛推荐用于SO):

from datetime import *
from dateutil import *
from dateutil.tz import *

# METHOD 1: Hardcode zones:
utc_zone = tz.gettz('UTC')
local_zone = tz.gettz('America/Chicago')
# METHOD 2: Auto-detect zones:
utc_zone = tz.tzutc()
local_zone = tz.tzlocal()

# Convert time string to datetime
local_time = datetime.strptime("2008-09-17 14:02:00", '%Y-%m-%d %H:%M:%S')

# Tell the datetime object that it's in local time zone since 
# datetime objects are 'naive' by default
local_time = local_time.replace(tzinfo=local_zone)
# Convert time to UTC
utc_time = local_time.astimezone(utc_zone)
# Generate UTC time string
utc_string = utc_time.strftime('%Y-%m-%d %H:%M:%S')

(代码源自Convert UTC datetime string to local datetime的答案)


17
投票

pytz的另一个例子,但包括localize(),这节省了我的一天。

import pytz, datetime
utc = pytz.utc
fmt = '%Y-%m-%d %H:%M:%S'
amsterdam = pytz.timezone('Europe/Amsterdam')

dt = datetime.datetime.strptime("2012-04-06 10:00:00", fmt)
am_dt = amsterdam.localize(dt)
print am_dt.astimezone(utc).strftime(fmt)
'2012-04-06 08:00:00'

12
投票

我在python-dateutil取得了最大的成功:

from dateutil import tz

def datetime_to_utc(date):
    """Returns date in UTC w/o tzinfo"""
    return date.astimezone(tz.gettz('UTC')).replace(tzinfo=None) if date.tzinfo else date

7
投票
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'
© www.soinside.com 2019 - 2024. All rights reserved.