Formatting milliseconds to certain String

Deniz Dogan kristnjov at nospam.com
Mon Feb 12 07:32:24 EST 2007


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:

def millisToFormat(millis):
     try:
         hours = millis / 3600000
         mins  = (millis - hours * 3600000) / 60000
         secs  = (millis - hours * 3600000 - mins * 60000) / 1000
         millis = millis - hours * 3600000 - mins * 60000 - secs * 1000
         hours = str(hours)
         mins = str(mins)
         secs = str(secs)
         millis = str(millis)
         if len(hours) == 1:
             hours = "0"+hours
         if len(mins) == 1:
             mins = "0"+mins
         if len(secs) == 1:
             secs = "0"+secs
         if len(millis) < 3:
             millis = (len(millis) - 3) * "0" + millis
         return str(hours) + ":" + str(mins) + ":" + str(secs) + "," + 
str(millis)
         except ValueError:
             return -1

Note that I am very new to Python and the language I have been using 
most prior to this is Java.

--Deniz Dogan



More information about the Python-list mailing list