Python Equivalent??

Jeff Epler jepler at
Wed Mar 10 04:24:41 CET 2004

Here are the tools you need:
>>> import time, calendar

First, parse the string into a time tuple:
>>> tup = time.strptime(d, pattern)
>>> tup
(2001, 1, 1, 13, 0, 0, 0, 1, -1)

Then, use calendar.timegm to convert it to seconds-since-epoch:
>>> calendar.timegm(tup)

Now, make sure everything went right:
>>> assert time.gmtime(_)[:6] == tup[:6]
(The slice takes the year, month, day, hour, minute and second fields)

Here's the final function:
    def convertDateTime(d, pattern="%Y-%m-%d %H:%M:%S"):
        tup = time.strptime(d, pattern)
        seconds = calendar.timegm(tup)
        assert time.gmtime(seconds)[:6] == tup[:6]
        return seconds

Or, for the terminally terse:
    def convertDateTime(d, p):
        return calendar.timegm(time.strptime(d, p))


More information about the Python-list mailing list