Formatting milliseconds to certain String

Duncan Booth duncan.booth at invalid.invalid
Mon Feb 12 07:59:46 EST 2007


Deniz Dogan <kristnjov at nospam.com> wrote:

> I want to make a function which takes an integer representing some
> time in milliseconds and returns the same time but formatted as 
> "hours:minutes:seconds,milliseconds" with leading zeros whenever
> possible. 
> 
> E.g. I input 185804 to the function and it returns 00:03:05,804. 

If you don't have to worry about more than 24 hours you could use 
strftime:

import time
def fmt(t):
    return time.strftime("%H:%M:%S",
        time.gmtime(t/1000)) + ',%03d' % (t%1000)

print fmt(185804)

If you do, then much as you had it but using a format string and floor 
division:

def fmt(t):
	SEC = 1000
	MIN = SEC * 60
	HOUR = MIN*60
	return "%02d:%02d:%02d,%03d" % (
		t//HOUR,
		(t%HOUR)//MIN,
		(t%MIN)//SEC,
		t%SEC)

Why did you write a function which returns a string normally and a 
number when it failed? Use an exception to indicate an error condition, 
not a number which you'll forget to check for.



More information about the Python-list mailing list