Formatting milliseconds to certain String

Robin Becker robin at reportlab.com
Mon Feb 12 08:03:18 EST 2007


Deniz Dogan wrote:
> Hello.
> I need help with a small problem I'm having.
> 
> 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. The 
> function I'm using now is defined as:
.......
> 
> Note that I am very new to Python and the language I have been using 
> most prior to this is Java.
> 
> --Deniz Dogan

how about

 >>> def millis2str(millis):
... 	hours, x = divmod(int(millis),3600000)
... 	mins, x = divmod(x,60000)
... 	secs, x = divmod(x,1000)
... 	s = '%02d:%02d:%02d' % (hours, mins,secs)
... 	if x: s += ',%03d' % x	
... 	return s
...
 >>> millis2str(185804)
'00:03:05,804'
 >>>
-- 
Robin Becker




More information about the Python-list mailing list