Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get UTC offset value from timezone?

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.

Now i want to find the UTC Offset value for the given Timezone, which in this case Asia/Calcutta is +5:30

I tried tzinfo() method as well, but i couldn't find the expected result. Can somebody guide me through this?

like image 602
kpokhrel Avatar asked Apr 10 '15 13:04

kpokhrel


People also ask

How do you find UTC offset?

Definition and Usage. getTimezoneOffset() returns the difference between UTC time and local time. getTimezoneOffset() returns the difference in minutes. For example, if your time zone is GMT+2, -120 will be returned.

How do you read timezone offset?

A common way to express a zone offset in field-based formats is with +/- followed by the offset. So for example, Japan is 9 hours ahead of UTC, so you may see a time written as 2016-06-11 05:10+09:00 .

What is offset value of timezone?

A zone offset is the difference in hours and minutes between a particular time zone and UTC. In ISO 8601, the particular zone offset can be indicated in a date or time value. The zone offset can be Z for UTC or it can be a value "+" or "-" from UTC.


Video Answer


1 Answers

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
like image 134
Samuel Littley Avatar answered Nov 15 '22 02:11

Samuel Littley