Storo
Storo

Reputation: 1008

How to get current offset of any timezone in Python

I need to get the current offset on any timezone in Python. At the moment I am using the pytz library and I am getting the offset with this code:

import datetime
import pytz
timezone = 'America/Punta_Arenas'
datetime.datetime.now(pytz.timezone(timezone)).utcoffset().total_seconds()/60/60
//prints -3
timezone = 'America/Santiago'
datetime.datetime.now(pytz.timezone(timezone)).utcoffset().total_seconds()/60/60
//prints -4

Taking as example 'America/Santiago': this year (2018), DST was set the 13 of May, while in 2015 DST was observed the whole year and in 2014 was set the 27 of April. So, sepending on the date and the year the offset is '-3' or '-4'.

I assume the previous code is not aware of the political decisions of each country regarding DST and probably gets you the offset according to fixed DST dates or something like that. Since I do not know how the nuts and bolts of datetime and pytz I'd rather ask, is this assumption right?

If it is not aware, how can I get the real current offset for any timezone?

Upvotes: 0

Views: 907

Answers (1)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241420

I assume the previous code is not aware of the political decisions of each country regarding DST and probably gets you the offset according to fixed DST dates or something like that.

Your assumption is incorrect. Political changes of time zones are recorded and distributed via the TZ Database. Those changes are then implemented in hundreds of different libraries, platforms, and operating systems - such as the pytz library you mention.

The change to America/Santiago that you describe was reflected in TZDB 2016c, which is implemented in pytz 2016.3. If you are using pytz 2016.3 or greater, then your code is aware of this change.

Pytz is fine, but you may want to consider using dateutil instead. Version 2.5.2 or higher has this data.

Upvotes: 2

Related Questions