In Python, I can find the Unix timestamp of local time knowing the timezone like this (using pytz):
>>> import datetime as DT >>> import pytz >>> mtl = pytz.timezone('America/Montreal') >>> naive_time3 = DT.datetime.strptime('2013/11/03', '%Y/%m/%d') >>> naive_time3 datetime.datetime(2013, 11, 3, 0, 0) >>> localized_time3 = mtl.localize(naive_time3) >>> localized_time3 datetime.datetime(2013, 11, 3, 0, 0, tzinfo=<DstTzInfo 'America/Montreal' EDT-1 day, 20:00:00 DST>) >>> localized_time3.timestamp() 1383451200.0
So far so good. naive_time does not know about the time zone, while localized_time knows its midnight on 2013/11/03 in Montreal , so the UTC Unix timestamp is good. This timezone is also my local timezone, and this timestamp seems to be correct:
$ date -d @1383451200 Sun Nov 3 00:00:00 EDT 2013
Now the clock was adjusted one hour ago on November 3 at 2 a.m. here in Montreal, so we got an extra hour that day. This means that there was 25 hours between 2013/11/03 and 2013/11/04. It shows:
>>> naive_time4 = DT.datetime.strptime('2013/11/04', '%Y/%m/%d') >>> localized_time4 = mtl.localize(naive_time4) >>> localized_time4 datetime.datetime(2013, 11, 4, 0, 0, tzinfo=<DstTzInfo 'America/Montreal' EST-1 day, 19:00:00 STD>) >>> (localized_time4.timestamp() - localized_time3.timestamp()) / 3600 25.0
Now I am looking for an easy way to get the localized_time4 object from localized_time3 , knowing that I want to get the next localized day at that hour (here, midnight), I tried timedelta , but I believe that it does not know about time zones or DST:
>>> localized_time4td = localized_time3 + DT.timedelta(1) >>> localized_time4td datetime.datetime(2013, 11, 4, 0, 0, tzinfo=<DstTzInfo 'America/Montreal' EDT-1 day, 20:00:00 DST>) >>> (localized_time4td.timestamp() - localized_time3.timestamp()) / 3600 24.0
My goal is to get information about the log entries that are stored in their Unix timestamp for each local day. Of course, if I use localized_time3.timestamp() and add 24 * 3600 here (which will be the same as localized_time4td.timestamp() ), I will skip all the log entries that occurred between localized_time4td.timestamp() and localized_time4td.timestamp() + 3600 .
In other words, the function or method I'm looking for should know when to add 25 hours, 24 hours, or 23 hours, sometimes to the Unix timestamp, depending on when the DST shifts occur.