在我的 Django 项目中,我有一个表单 (forms.py) 它实现了 pytz 来获取当前时区,如下所示:
tz = timezone.get_current_timezone()
我已将此值作为初始值传递给表单字段,如下所示:
timezone = forms.CharField(label='Time Zone', initial=tznow)
这为该字段提供了当前时区的默认值,在我的情况下,它恰好是 亚洲/加尔各答 .
现在我想找到给定时区的 UTC 偏移值,在本例中为 亚洲/加尔各答是 +5:30
我也尝试了 tzinfo() 方法,但找不到预期的结果。有人可以指导我完成这个吗?
最佳答案
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
关于django - 如何从时区获取UTC偏移值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29563277/