Convert a date to epoch

it seems like an easy quest, ain't it? well, it took me far too long to get it done, so let just write it down, so that maybe I won't forget in 2 seconds:
>>> import time
>>> str = '2009-03-04'
>>> format = '%Y-%m-%d'
>>> time.mktime(time.strptime(str, format))
>>> int(_)
and here you have your epoch (if you just need seconds, use int()).


James Brown said...

Alternatively, `date -d'2009-03-04' '+%s'`

Anonymous said...

This recipe is incorrect, sorry. :/

Consider this edge case and it becomes a bit more obvious:

>>> fmt = '%Y-%m-%d'
>>> str = '1970-01-01'
>>> mktime(strptime(str, fmt))

Clearly the value for Jan 1, 1970 should be 0. The trouble is that mktime assumes a time tuple in localtime, whereas epoch offsets are always GMT or UTC. You need to adjust for your local timezone. This gets to be prohibitively complex as you desire more accuracy (for example, mktime(gmtime(0)) tells you how offset your local timezone was on Jan 1, 1970, but that's not necessarily the same as the offset for the actual date you're operating on - DST is a major (but not the only) factor in throwing that off).

SEJeff said...

overwriting python's built in types is very poor form. Try:
s = '1970-01-01'

string = '1970-01-01'

Anonymous said...

I also wanted a way to look up these conversions, so I made a more general tool:

Sandro Tosi said...

I'm just adding what Joss suggested on IRC:

>>> from datetime import datetime
>>> string = '2009-03-04'
>>> format = '%Y-%m-%d'
>>> datetime.strptime(string, format).strftime('%s')

Sandro Tosi said...

and here's the comment of Wayne Witzel at http://pieceofpy.com/2010/12/29/response-convert-date-to-epoch :

>>> import time, calendar
>>> ts = time.strptime('2010-12-01', '%Y-%m-%d')
>>> calendar.timegm(ts)
>>> ts = time.strptime('1970-01-01', '%Y-%m-%d')
>>> calendar.timegm(ts)

PS: thanks to all that have commented and/or criticizes the recipe :)