Skip to content

Instantly share code, notes, and snippets.

@rvteja92
Last active May 4, 2018 08:10
Show Gist options
  • Save rvteja92/2310e60bcc3819fc176af4fce382e691 to your computer and use it in GitHub Desktop.
Save rvteja92/2310e60bcc3819fc176af4fce382e691 to your computer and use it in GitHub Desktop.
Python and Timezones - with Django and Pytz - working with daylight saving time

Working around varying timezone offset (daylight saving time)

Create a pytz.timezone object

>> import pytz
>> tz = pytz.timezone('Asia/Kolkata')
>> tz
<DstTzInfo 'Asia/Kolkata' HMT+5:53:00 STD>

As you can see the original offset of the zone 'Asia/Kolkata' is +5:53. But the problem arises with the fact that the current offset (4th May, 2018) for the zone is +5:30. Here's the problem.

>> from datetime import datetime

>> dt_str = '2018-05-04 8:30 AM'
>> dt_obj = datetime.strptime(dt_str, '%Y-%m-%d %I:%M %p')
>> dt_obj
datetime.datetime(2018, 5, 4, 8, 30)

>> local_dt = dt_obj.replace(tzinfo=tz)
>> local_dt
datetime.datetime(2018, 5, 4, 8, 30, tzinfo=<DstTzInfo 'Asia/Kolkata' HMT+5:53:00 STD>)

>> local_dt.utctimetuple()
time.struct_time(tm_year=2018, tm_mon=5, tm_mday=4, tm_hour=2, tm_min=37, tm_sec=0, tm_wday=4, tm_yday=124, tm_isdst=0)

You see the problem? The UTC time is time.struct_time(tm_year=2018, tm_mon=5, tm_mday=4, tm_hour=2, tm_min=37, tm_sec=0, tm_wday=4, tm_yday=124, tm_isdst=0) when it actually should have been time.struct_time(tm_year=2018, tm_mon=5, tm_mday=4, tm_hour=3, tm_min=0, tm_sec=0, tm_wday=4, tm_yday=124, tm_isdst=0).

Here is how to work around the problem. We need to use the pytz.timezone's localize() method instead of datetime's replace() method.

>> correct_dt = tz.localize(dt_obj)
>> correct_dt
datetime.datetime(2018, 5, 4, 8, 30, tzinfo=<DstTzInfo 'Asia/Kolkata' IST+5:30:00 STD>)

>> correct_dt.utctimetuple()
time.struct_time(tm_year=2018, tm_mon=5, tm_mday=4, tm_hour=3, tm_min=0, tm_sec=0, tm_wday=4, tm_yday=124, tm_isdst=0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment