【问题标题】:how to get UTC offset value from timezone?如何从时区获取 UTC 偏移值?
【发布时间】:2015-06-16 06:45:21
【问题描述】:

在我的 Django 项目中,我有一个表单 (forms.py) 实现 pytz 以获取当前时区,如下所示:

tz = timezone.get_current_timezone()

我已将此值作为初始值传递给表单字段,如下所示:

timezone = forms.CharField(label='Time Zone', initial=tznow)

它为该字段提供当前时区的默认值,在我的例子中,它恰好是 Asia/Calcutta

现在我想找到给定时区的 UTC 偏移值,在这种情况下 Asia/Calcutta+5:30

我也尝试了 tzinfo() 方法,但我找不到预期的结果。有人可以指导我吗?

【问题讨论】:

    标签: django python-2.7


    【解决方案1】:

    UTC 偏移量由 tzinfo 的任何实现(例如 pytz)的 utcoffset 方法作为 timedelta 给出。例如:

    import pytz
    import datetime
    
    tz = pytz.timezone('Asia/Calcutta')
    dt = datetime.datetime.utcnow()
    
    offset_seconds = tz.utcoffset(dt).seconds
    
    offset_hours = offset_seconds / 3600.0
    
    print "{:+d}:{:02d}".format(int(offset_hours), int((offset_hours % 1) * 60))
    # +5:30
    

    【讨论】:

    • 谢谢伙计。当我打印 offset_hours 时,它给出:5.5 & 它的浮点类型。现在如何在不改变类型的情况下将其更改为 +5.5 ?
    • (1) 将 UTC 时间传递给 tz.utcoffset() 是不正确的,除非 tz = pytz.utc (2) .seconds 对于负偏移量是错误的(.days-1) (3) 否这里需要使用浮点数(使用divmod())。
    【解决方案2】:

    Asia/Calcutta 等单个时区在不同日期可能具有不同的 UTC 偏移量。在这种情况下,您可以使用pytz_tzinfos 枚举迄今为止已知的UTC 偏移量:

    >>> offsets = {off for off, dst, abbr in pytz.timezone('Asia/Calcutta')._tzinfos}
    >>> for utc_offset in offsets:
    ...     print(utc_offset)
    ... 
    5:30:00
    6:30:00
    5:53:00
    

    获取给定时区的当前 UTC 偏移量:

    #!/usr/bin/env python
    from datetime import datetime
    import pytz # $ pip install pytz
    
    utc_offset = datetime.now(pytz.timezone('Asia/Calcutta')).utcoffset()
    print(utc_offset)
    # -> 5:30:00
    

    【讨论】:

      【解决方案3】:

      如果您只想要标准化的小时偏移量:

      def curr_calcutta_offset():
          tz_calcutta = pytz.timezone('Asia/Calcutta')
          offset = tz_calcutta.utcoffset(datetime.utcnow())
          offset_seconds = (offset.days * 86400) + offset.seconds
          offset_hours = offset_seconds / 3600
      
          return offset_hours
      
      curr_calcutta_offset()
      # 5.5
      

      【讨论】:

        猜你喜欢
        • 2016-05-07
        • 2013-10-15
        • 1970-01-01
        • 1970-01-01
        • 2019-04-23
        • 1970-01-01
        • 1970-01-01
        • 2016-01-06
        • 2011-07-29
        相关资源
        最近更新 更多