Tuesday, February 2, 2010

Seconds since epoch from Python datetime

My naive approach, given a naive Python date:
$ cat > t.py
from datetime import datetime
dt = datetime(2010,2,2,13,52,39)
dt.strftime("%s")
^D
$ python t.py
1265136759
But that's not right:
$ TZ=GMT date -r 1265136759
Tue Feb  2 18:52:39 GMT 2010
$
To get the correct seconds, you need to first set timezone to GMT.
$ cat > t.py
import os
from datetime import datetime

oldtz = ''
if os.environ.has_key('TZ'):
    oldtz = os.environ['TZ']
os.environ['TZ'] = 'GMT'
dt = datetime(2010,2,2,13,52,39)
print dt.strftime("%s")
if oldtz:
    os.environ['TZ'] = oldtz
else:
    del os.environ['TZ']
$ python t.py
1265118759
$ TZ=GMT date -r 1265118759
Tue Feb  2 13:52:39 GMT 2010
$
The difference in these two second values is 5 hours, which is my local time zone offset from GMT. So although the Python date has no timezone information, when Python's strftime() converts it to seconds since epoch, it uses the local timezone instead of GMT. I consistently find dates and times to be tricky when programming.