【问题标题】:Getting computer's UTC offset in Python在 Python 中获取计算机的 UTC 偏移量
【发布时间】:2011-03-11 05:34:57
【问题描述】:

在 Python 中,如何找到计算机设置的 UTC 时间偏移量?

【问题讨论】:

    标签: python timezone utc


    【解决方案1】:

    time.timezone:

    import time
    
    print -time.timezone
    

    它以秒为单位打印 UTC 偏移量(考虑夏令时 (DST),请参阅 time.altzone:

    is_dst = time.daylight and time.localtime().tm_isdst > 0
    utc_offset = - (time.altzone if is_dst else time.timezone)
    

    其中 utc 偏移量通过以下方式定义:“要获取本地时间,请将 utc 偏移量添加到 utc 时间。”

    在 Python 3.3+ 中有 tm_gmtoff attribute 如果底层 C 库支持它:

    utc_offset = time.localtime().tm_gmtoff
    

    注意:time.daylight 可能会在some edge cases 中给出错误的结果。

    tm_gmtoff 如果在 Python 3.3+ 上可用,则由 datetime 自动使用:

    from datetime import datetime, timedelta, timezone
    
    d = datetime.now(timezone.utc).astimezone()
    utc_offset = d.utcoffset() // timedelta(seconds=1)
    

    要以一种解决time.daylight 问题的方法获取当前UTC 偏移量,并且即使tm_gmtoff 不可用也可以使用,@jts's suggestion 可用于子结构本地和UTC 时间:

    import time
    from datetime import datetime
    
    ts = time.time()
    utc_offset = (datetime.fromtimestamp(ts) -
                  datetime.utcfromtimestamp(ts)).total_seconds()
    

    要获取过去/未来日期的 UTC 偏移量,可以使用 pytz 时区:

    from datetime import datetime
    from tzlocal import get_localzone # $ pip install tzlocal
    
    tz = get_localzone() # local timezone 
    d = datetime.now(tz) # or some other local date 
    utc_offset = d.utcoffset().total_seconds()
    

    它在 DST 转换期间有效,它适用于过去/未来的日期,即使当地时区在当时有不同的 UTC 偏移量,例如 2010-2015 年期间的欧洲/莫斯科时区。

    【讨论】:

    【解决方案2】:

    gmtime() 将返回 UTC 时间,localtime() 将返回本地时间,因此减去两者应该会得到 UTC 偏移量。

    来自https://pubs.opengroup.org/onlinepubs/009695399/functions/gmtime.html

    gmtime() 函数应将自计时器指向的纪元以来的时间(以秒为单位)转换为细分时间,以协调世界时 (UTC) 表示。

    因此,尽管名称为 gmttime,该函数仍返回 UTC。

    【讨论】:

    • 减去它们得到TypeError: unsupported operand type(s) for -: 'time.struct_time' and 'time.struct_time'。你的真正意思是什么?
    • rakslice,试试 calendar.timegm(time.gmtime()) - calendar.timegm(time.localtime()))
    • @Kirby:gmtime() returns UTC always。有些情况下 GMT!=UTC 但不是这样。
    • 给事物命名很难,我猜。感谢您的澄清
    【解决方案3】:

    我喜欢:

    >>> strftime('%z')
    '-0700'
    

    我首先尝试了 JTS 的答案,但它给了我错误的结果。我现在在-0700,但有人说我在-0800。但是我必须进行一些转换才能得到可以减去的东西,所以答案可能比不正确更不完整。

    【讨论】:

    • '%z' 不受 Python 支持(它可能适用于您可能可以使用 time.localtime().tm_gmtoff 代替的某些系统,以将 utc 偏移量作为数字而不是字符串获取)。结果('%z')应该与@jts 的答案相同。如果您不这么认为,请包含您的代码。
    • 导入时间 time0 = time.time() utc_time = time.mktime(time.gmtime(time0)) local_time = time.mktime(time.localtime(time0)) offset = local_time - utc_time print( offset / (60 * 60)) 给出 -8。
    • 1.不要将代码放在 cmets 中,而是更新您的答案 2. 这里使用 mktime() 是不正确的,使用 calendar.timegm()datetime() 来查找差异
    【解决方案4】:

    time module 有一个时区偏移量,以整数形式给出,单位为“UTC 以西的秒数”

    import time
    time.timezone
    

    【讨论】:

    • 这不包括夏令时调整
    【解决方案5】:

    您可以使用datetimedateutil 库将偏移量作为timedelta 对象:

    >>> from datetime import datetime
    >>> from dateutil.tz import tzlocal
    >>>
    >>> # From a datetime object
    >>> current_time = datetime.now(tzlocal())
    >>> current_time.utcoffset()
    datetime.timedelta(seconds=7200)
    >>> current_time.dst()
    datetime.timedelta(seconds=3600)
    >>>
    >>> # From a tzlocal object
    >>> time_zone = tzlocal()
    >>> time_zone.utcoffset(datetime.now())
    datetime.timedelta(seconds=7200)
    >>> time_zone.dst(datetime.now())
    datetime.timedelta(seconds=3600)
    >>>
    >>> print('Your UTC offset is {:+g}'.format(current_time.utcoffset().total_seconds()/3600))
    Your UTC offset is +2
    

    【讨论】:

      【解决方案6】:
      hours_delta = (time.mktime(time.localtime()) - time.mktime(time.gmtime())) / 60 / 60
      

      【讨论】:

      • GMT != UTC。 GMT 有夏令时。 UTC 没有。
      • 其实GMT和UTC是一样的。在英国,我们有英国夏令时 (BST) 用于夏令时。例如,请参阅 greenwichmeantime.com/what-is-gmt,其中显示“GMT(夏令时从不适用)”。
      【解决方案7】:

      使用 UTC 更正时区创建 Unix 时间戳

      这个简单的函数可以让您轻松地从 MySQL/PostgreSQL 数据库date 对象中获取当前时间。

      def timestamp(date='2018-05-01'):
          return int(time.mktime(
              datetime.datetime.strptime( date, "%Y-%m-%d" ).timetuple()
          )) + int(time.strftime('%z')) * 6 * 6
      

      示例输出

      >>> timestamp('2018-05-01')
      1525132800
      >>> timestamp('2018-06-01')
      1527811200
      

      【讨论】:

        【解决方案8】:

        这里是一些只有日期时间和时间作为导入的 python3 代码。高温

        >>> from datetime import datetime
        >>> import time
        >>> def date2iso(thedate):
        ...     strdate = thedate.strftime("%Y-%m-%dT%H:%M:%S")
        ...     minute = (time.localtime().tm_gmtoff / 60) % 60
        ...     hour = ((time.localtime().tm_gmtoff / 60) - minute) / 60
        ...     utcoffset = "%.2d%.2d" %(hour, minute)
        ...     if utcoffset[0] != '-':
        ...         utcoffset = '+' + utcoffset
        ...     return strdate + utcoffset
        ... 
        >>> date2iso(datetime.fromtimestamp(time.time()))
        '2015-04-06T23:56:30-0400'
        

        【讨论】:

          【解决方案9】:

          这对我有用:

          if time.daylight > 0:
                  return time.altzone
              else:
                  return time.timezone
          

          【讨论】:

          • 对不起,你的帖子太长太完整了,我不明白这是同一个答案。我的帖子肯定是同一解决方案的较短版本。
          • 不,代码错误。 time.daylight 没有说现在是不是夏天。它说当地时间可能有夏令时。这就是为什么你必须打电话给time.localtime().tm_isdst
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-07-26
          • 2011-07-29
          • 2020-10-21
          • 2014-01-09
          • 2016-07-06
          相关资源
          最近更新 更多