Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get UTC offset from time zone name in python

Tags:

python

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

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

like image 948
alexarsh Avatar asked Apr 04 '11 11:04

alexarsh


People also ask

How do you find UTC offset?

The JavaScript getTimezoneOffset() method is used to find the timezone offset. It returns the timezone difference in minutes, between the UTC and the current local time. If the returned value is positive, local timezone is behind the UTC and if it is negative, the local timezone if ahead of UTC.

How do I set UTC time zone in Python?

You can also use the pytz module to create timezone-aware objects. For this, we will store the current date and time in a new variable using the datetime. now() function of datetime module and then we will add the timezone using timezone function of pytz module.


2 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) 
like image 179
eumiro Avatar answered Sep 19 '22 21:09

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 
like image 32
Jon Skeet Avatar answered Sep 17 '22 21:09

Jon Skeet