如何从时区获取UTC偏移值? [英] how to get UTC offset value from timezone?
问题描述
在我的Django项目中,我有一个表单 (forms.py) ,它实现了pytz来获取当前时区,如下所示:
In my Django project, I have a form (forms.py) which implements pytz to get current timezone like this:
tz = timezone.get_current_timezone()
我已经将此值传递给一个表单域作为初始值,如下所示:
and I have passed this value to a form field as an initial value like this:
timezone = forms.CharField(label='Time Zone', initial=tznow)
这个字段是当前时区的默认值,我的情况,它恰好是亚洲/加尔各答。
which gives the field a default value of current Timezone, in my case, it happens to be Asia/Calcutta.
现在我想找到给定时区的UTC偏移值,在这里case 亚洲/加尔各答是 +5:30
Now i want to find the UTC Offset value for the given Timezone, which in this case Asia/Calcutta is +5:30
我也尝试过tzinfo()方法,但我couldn找不到预期的结果。有人可以指导我完成这个吗?
I tried tzinfo() method as well, but i couldn't find the expected result. Can somebody guide me through this?
推荐答案
UTC偏移由utcoffset方法作为timedelta作为tzinfo的任何实现作为pytz。例如:
The UTC offset is given as a timedelta by the utcoffset method of any implementation of tzinfo such as pytz. For example:
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
这篇关于如何从时区获取UTC偏移值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!