Python Equivalent??
Jeff Epler
jepler at unpythonic.net
Tue Mar 9 22:24:41 EST 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)
978354000
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))
Jeff
More information about the Python-list
mailing list