Formatting milliseconds to certain String

Laurent Pointal laurent.pointal at limsi.fr
Mon Feb 12 08:06:46 EST 2007


Deniz Dogan a écrit :
> 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.

A shorter solution using % operator in Python:

>>> def millisToFormat(millis):
...     hours = millis / 3600000
...     mins  = (millis - hours * 3600000) / 60000
...     secs  = (millis - hours * 3600000 - mins * 60000) / 1000
...     millis = millis - hours * 3600000 - mins * 60000 - secs * 1000
...     return "%(hours)02d:%(mins)02d:%(secs)02d,%(millis)03d"%locals()
...
>>> millisToFormat(185804 )
'00:03:05,804'

See chapter "3.6.2 String Formatting Operations" in the Python Library
Reference.

http://docs.python.org/lib/typesseq-strings.html

A+

Laurent.




More information about the Python-list mailing list