Get UTC offset from time zone name in python

Question:

How can I get UTC offset from time zone name in python?

For example: I have Asia/Jerusalem and I want to get +0200

Asked By: alexarsh

||

Answers:

Because of DST (Daylight Saving Time), the result depends on the time of the year:

import datetime, pytz

datetime.datetime.now(pytz.timezone('Asia/Jerusalem')).strftime('%z')

# returns '+0300' (because 'now' they have DST)


pytz.timezone('Asia/Jerusalem').localize(datetime.datetime(2011,1,1)).strftime('%z')

# returns '+0200' (because in January they didn't have DST)
Answered By: eumiro

Have you tried using the pytz project and the utcoffset method?

e.g.

>>> import datetime
>>> import pytz
>>> pacific_now = datetime.datetime.now(pytz.timezone('US/Pacific'))
>>> pacific_now.utcoffset().total_seconds()/60/60
-7.0
Answered By: Jon Skeet

I faced a similar issue while converting to UTC timestamp from python datetime object. My datetime was timezone agnostic (very naive) and as such astimezone would not work.

To mitigate the issue, I made my datetime object timezone aware and then used the above magic.

import pytz
system_tz = pytz.timezone(constants.TIME_ZONE)
localized_time = system_tz.localize(time_of_meeting)
fmt = "%Y%m%dT%H%M%S" + 'Z'
return localized_time.astimezone(pytz.utc).strftime(fmt)

Here, constants.TIME_ZONE is where I had the default timezone of my persisted objects.

Hope this helps someone attempting to convert python datetime objects to UTC. Once converted, format any way you please.

Answered By: Rohan Bagchi

Another perspectife from @Jon Skeet answer, assuming you already have datetime.datetime object, for example day = datetime.datetime(2021, 4, 24):

import pytz
tz = pytz.timezone("Asia/Kolkata")

import datetime
day = datetime.datetime(2021, 4, 24)

offset = tz.utcoffset(day)/3600
Answered By: Muhammad Yasirroni

Another way to get UTC Offset as an integer:

import datetime
import pytz
from tzwhere import tzwhere

tzwhere = tzwhere.tzwhere()
timezone = pytz.timezone('Asia/Jerusalem')
offSet_str = str(timezone.utcoffset(datetime.datetime.now()))
if offSet_str[0] != '-':
    offSet = int(offSet_str[0])
else:
    offSet = int(offSet_str[8] + offSet_str[9]) - 24

print(offSet)

Jon Skeet has a faster method

Answered By: William Mears
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.