How can I get UTC offset from time zone name in python?
For example: I have Asia/Jerusalem
and I want to get +0200
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.
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.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With