Format seconds to time with milliseconds in python

Sat Mar 5, 2016

When you need to create video subtitles in https://en.wikipedia.org/wiki/SubRip format the timecode needs to be hours:minutes:seconds,milliseconds, like 01:02:03,456.

I generally store the times in milliseconds so we don’t have to deal with floats or strings. But when you want to to format these, there are number of different ways to do it. One way is to leverage the python datetime package like this:

def fmttime(millisecs):
    secs = millisecs / 1000.0
    d = datetime.timedelta(seconds=secs)
    t = (datetime.datetime.min + d).time()
    milli = t.strftime('%f')[:3]
    value = t.strftime('%H:%M:%S,') + milli
    return value