Here is a small footprint routine to convert a number of floating point seconds (such as an elapsed time, found by subtracting an earlier return value from time.time() from a later value) to "0:00:00.000" format, instead of "time.strftime("%H:%M:%S",time.gmtime(t2-t1))+(".%03d" % (((t2-t1)-int(t2-t1))*1000))"
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | def secondsToStr(t):
rediv = lambda ll,b : list(divmod(ll[0],b)) + ll[1:]
return "%d:%02d:%02d.%03d" % tuple(reduce(rediv,[[t*1000,],1000,60,60]))
# example usage
import time
t1 = time.time()
# perform long-running task
t2 = time.time()
print "Elapsed time:", secondsToStr( t2-t1 )
|
strftime has no % code for milliseconds, so one must compute that separately and append. Plus, I always have to look up those % codes in the docs! This recipe could be easily extended to include a leading number of days (if your application routinely has such elapsed times), or format the leading hours field to be a fixed length (such as %3d instead of just %d) to make printouts neater.