Difference between two times (working ugly code, needs polish)
Shawn Milochik
Shawn at Milochik.com
Tue Sep 11 16:46:52 EDT 2007
I have done what I wanted, but I think there must be a much better way.
Given two timestamps in the following format, I just want to figure
out how far apart they are (in days, seconds, whatever).
Format:
YYYY-MM-DD_MM:SS
Example:
2007-09-11_16:41
It seems to me that to do what I want, I need to convert a string into
a number (time.mktime()), such as this: 1189543487.0
Once I have that, I can just subtract one from the other and do
whatever I want. The ugly part is converting something like
2007-09-11_16:41 to the numeric equivalent.
Below is my code. Any suggestions?
Thanks in advance.
Here is what I have (works):
#runTimeStamp is the current time, set when the script begins execution
def recAge(lastUpdate, runTimeStamp):
import re
oneDay = 60 * 60 * 24
lastUpdate = re.sub(r'\D+', ',', lastUpdate)
lastUpdate = lastUpdate + ",0,0,0,0"
lastUpdate = [int(x) for x in lastUpdate.split(',')]
lastUpdate = time.mktime(tuple(lastUpdate))
runTimeStamp = re.sub(r'\D+', ',', runTimeStamp)
runTimeStamp = runTimeStamp + ",0,0,0,0"
runTimeStamp = [int(x) for x in runTimeStamp.split(',')]
runTimeStamp = time.mktime(tuple(runTimeStamp))
return (runTimeStamp - lastUpdate) / oneDay
More information about the Python-list
mailing list