如何从时区获取UTC偏移值?

kpo*_*rel 5 django python-2.7

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

tz = timezone.get_current_timezone()
Run Code Online (Sandbox Code Playgroud)

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

timezone = forms.CharField(label='Time Zone', initial=tznow)
Run Code Online (Sandbox Code Playgroud)

这为该字段提供了当前时区的默认值,在我的情况下,它恰好是Asia/Calcutta

现在我想找到给定时区的 UTC 偏移值,在这种情况下亚洲/加尔各答+5:30

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

Sam*_*ley 7

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
Run Code Online (Sandbox Code Playgroud)

  • (1) 将 UTC 时间传递给 `tz.utcoffset()` 是不正确的,除非 `tz = pytz.utc` (2) `.seconds` 对于负偏移量是错误的 (`.days` 是 `-1`) ( 3)这里不需要使用浮点数(使用`divmod()`)。 (2认同)

jfs*_*jfs 5

例如,单个时区Asia/Calcutta在不同日期可能具有不同的 utc 偏移量。在这种情况下,您可以使用pytz's枚举迄今为止已知的 utc 偏移量_tzinfos

>>> 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
Run Code Online (Sandbox Code Playgroud)

要获取给定时区的当前 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
Run Code Online (Sandbox Code Playgroud)