kpp9c wrote: > Hi, > > I was looking at python & datetime and hoping that it would already > have > a method/func to translate time formats. I need to translate seconds > to hh:mm:ss.ms and vice versa and would like the ability to do some > basic arithmetic in these formats. I think that there just has to be a > package > or module out there that already does this with reasonable speed and > accuracy. > > Sadly, i do indeed need both reasonable speed and accuracy since i > will be adding up huge masses of small events (around 10 to 60 ms > milliseconds > in length) to create cloud like textures for real time audio/video at > high sampling rates. > > i googled for hh:mm:ss.ms + python and didn't find much... > > best, > > -kp--- > > [mac os x w/ python 2.4.1]
Hmmm ... not difficult to do, but it's the "speed" bit that's tricky. Here's quick and dirty implementation, but I wouldn't place any bets on it being fast (or accurate enough for that matter!) #!/bin/env python # vim: set noet sw=4 ts=4: import datetime def secs2time(s): ms = int((s - int(s)) * 1000000) s = int(s) # Get rid of this line if s will never exceed 86400 while s >= 24*60*60: s -= 24*60*60 h = s / (60*60) s -= h*60*60 m = s / 60 s -= m*60 return datetime.time(h, m, s, ms) def time2secs(d): return d.hour*60*60 + d.minute*60 + d.second + \ (float(d.microsecond) / 1000000) if __name__ == "__main__": for i in (80000.123, 0.0, 5873, 12345.6789): print "%12.6f -> %15s -> %12.6f" % ( i, secs2time(i), time2secs(secs2time(i)) ) assert i == time2secs(secs2time(i)) from timeit import Timer timer = Timer( setup="from __main__ import time2secs, secs2time", stmt="time2secs(secs2time(12345.6789))") count = 1000000 total = timer.timeit(count) print "Time for %d invocations: %.10fs" % (count, total) print "Time per invocation: %.10fs" % (total / count,) And the output: 80000.123000 -> 22:13:20.123000 -> 80000.123000 0.000000 -> 00:00:00 -> 0.000000 5873.000000 -> 01:37:53 -> 5873.000000 12345.678900 -> 03:25:45.678900 -> 12345.678900 Time for 1000000 invocations: 9.3959178925s Time per invocation: 0.0000093959s Huh ... what d'ya know ... good thing I ain't a betting man! Dave. -- -- http://mail.python.org/mailman/listinfo/python-list