Formatting milliseconds to certain String

John Machin sjmachin at lexicon.net
Mon Feb 12 08:16:52 EST 2007


On Feb 12, 11:32 pm, Deniz Dogan <kristn... at nospam.com> 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.


| >>> def fmt_millis(millis):
| ...     """millis is an integer number of milliseconds.
| ...     Return str hh:mm:ss,ttt
| ...     """
| ...     seconds, millis = divmod(millis, 1000)
| ...     minutes, seconds = divmod(seconds, 60)
| ...     hours, minutes = divmod(minutes, 60)
| ...     return "%02d:%02d:%02d,%03d" % (hours, minutes, seconds,
millis)
| ...
| >>> fmt_millis(0)
| '00:00:00,000'
| >>> fmt_millis(1)
| '00:00:00,001'
| >>> fmt_millis(12345678)
| '03:25:45,678'
| >>> fmt_millis(45678)
| '00:00:45,678'
| >>> fmt_millis(1230000)
| '00:20:30,000'
| >>> fmt_millis(3600000)
| '01:00:00,000'
| >>> fmt_millis(3600000*24)
| '24:00:00,000'
| >>> fmt_millis(3600000*2400)
| '2400:00:00,000'
| >>>




More information about the Python-list mailing list