首页 文章

如何在Python中将本地时间转换为UTC?

提问于
浏览
239

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

我敢肯定我以前做过这个,但是找不到它,所以希望将来帮助我(以及其他人)做到这一点 .

Clarification :例如,如果我的本地时区( +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时间的唯一转换 .

17 回答

  • 59

    如果您更喜欢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")
    
  • 23

    我很幸运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

    为了避免日光节约等

    上述答案都没有给我带来特别的帮助 . 以下代码适用于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>)
    
  • 17

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

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

    • struct_time(UTC)→POSIX:
      calendar.timegm(struct_time)

    • Naïvedatetime(local)→POSIX(s):
      calendar.timegm(stz.localize(dt, is_dst=None).utctimetuple())
      (在DST转换期间的异常,请参阅jfs的注释)

    • Naïvedatetime(UTC)→POSIX(s):
      calendar.timegm(dt.utctimetuple())

    • 意识到日期时间→POSIX:
      calendar.timegm(dt.utctimetuple())

    • POSIX→struct_time(UTC,s):
      time.gmtime(t)
      (参见jfs的评论)

    • Naïvedatetime(local)→struct_time(UTC,s):
      stz.localize(dt, is_dst=None).utctimetuple()
      (在DST转换期间的异常,请参阅jfs的注释)

    • Naïvedatetime(UTC)→struct_time(UTC,s):
      dt.utctimetuple()

    • 感知日期时间→struct_time(UTC,s):
      dt.utctimetuple()

    • POSIX→天真日期时间(本地):
      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的评论)

    • Naïvedatetime(UTC)→Naïvedatetime(local):
      dt.replace(tzinfo=UTC).astimezone(tz).replace(tzinfo=None)

    • Aware datetime→Naïvedatetime(local):
      dt.astimezone(tz).replace(tzinfo=None)

    • POSIX→天真日期时间(UTC):
      datetime.utcfromtimestamp(t)

    • struct_time(UTC)→Naïvedatetime(UTC,s):
      datetime.datetime(*struct_time[:6])
      (不能代表闰秒,请参阅jfs的评论)

    • Naïvedatetime(本地)→Naïvedatetime(UTC):
      stz.localize(dt, is_dst=None).astimezone(UTC).replace(tzinfo=None)
      (在DST转换期间的异常,请参阅jfs的注释)

    • Aware datetime→Naïvedatetime(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

  • 28

    在python3中:

    pip install python-dateutil

    from dateutil.parser import tz
    
    mydt.astimezone(tz.gettz('UTC')).replace(tzinfo=None)
    
  • 211
    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'
    
  • 3

    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'
    
  • 1

    简单

    我是这样做的:

    >>> 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
    
  • 3

    你可以这样做:

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

    怎么样 -

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

    如果seconds是 None ,那么它将本地时间转换为UTC时间,否则将传入的时间转换为UTC .

  • 108

    首先,将字符串解析为一个天真的日期时间对象 . 这是 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")
    
  • 2

    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格式测量和存储时间 . 如果您需要记录拍摄时间,请单独存储 . 不要存储本地时间时区信息!

    NOTE - 如果您的任何数据位于使用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'
    

    如果您准备好接受时区转换,请阅读以下内容:

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

  • 7

    使用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')
    

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

  • 2

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

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

    谢谢@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
    自epoch以来的秒数 - >当地时区的元组

  • 13
    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())
    
  • 0

    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
    

相关问题