Converting a string to time - simple task but don't know how to do it!

Peter Hansen peter at
Sat Sep 14 16:44:30 EDT 2002

Richard Kessler wrote:
> I have a string returned from a database expressing the time i.e. 2002-09-14
> 10:30:34.  I need to compare this value to the current time to determine the
> amount of time elapsed between the two. I get the current time using
> time.time() but I cannot find a way to convert the string from the database
> into a time value (seconds from epoch) to do the simple subraction to find
> seconds elapsed.

If the format is exactly that, you could use something primitive like this:

 >>> s = '2002-09-14 10:30:34'
 >>> import re, time
 >>> tt = tuple(map(int, re.findall('(....)-(..)-(..) (..):(..):(..)', 
s)[0]) + [0,0,0])
 >>> time.mktime(tt)


More information about the Python-list mailing list