David Ferris
David Ferris

Reputation: 2325

Python datetime: convert milliseconds to string, preserving zeroes

I'd like to convert a number of milliseconds to a formatted string using Python's datetime.

def milliseconds_to_str(t):
     """Converts the number of milliseconds to HH:MM:SS,ms time"""
     return str(datetime.timedelta(milliseconds=t)).replace('.', ',')[:-3]

The above works extremely well, for example:

> milliseconds_to_str(8712313): '2:25:12,313'

The problem arises when the number of milliseconds is an even multiple of 1000, for example:

milliseconds_to_srt_time(1000) > 0:00 (Should be 0:00:01,000)
milliseconds_to_srt_time(1000000) > 0:16 (Should be 0:16:00,000)
milliseconds_to_srt_time(4000400) > 1:06:40,400 (GOOD)
milliseconds_to_srt_time(80808231) > 22:26:48,231 (GOOD)
milliseconds_to_srt_time(80808000) > 22:26 (Should be 22:26:00,000)

How can I avoid this rounding?

Upvotes: 1

Views: 163

Answers (2)

Phildeal
Phildeal

Reputation: 26

Here is another exemple of implementation, very similar though.

You can find other usefull information here : Format timedelta to string

import datetime

def milliseconds_to_str(t):
    """Converts the number of milliseconds to HH:MM:SS,ms time"""
    d = str(datetime.timedelta(milliseconds=t)).split(".")
    out = ":".join(["%02d" % (int(float(x))) for x in d[0].split(':')])
    return out + "," + ("%d" % (int(d[1])/1000) if len(d)==2 else "000")

print(milliseconds_to_str(8712313))
print(milliseconds_to_str(1000))
print(milliseconds_to_str(1000000))  
print(milliseconds_to_str(4000400)) 
print(milliseconds_to_str(80808231)) 
print(milliseconds_to_str(80808000))

The output is the same as Niel gave.

Upvotes: 0

Niel Godfrey P. Ponciano
Niel Godfrey P. Ponciano

Reputation: 10699

Using a fixed slicing of [:-3] wouldn't work because the resulting string of the milliseconds varies.

2:25:12.313000
0:00:01

Here, it will only be applicable to the 1st (where the last 000 would be trimmed resulting to 2:25:12.313) but should not be applied on the 2nd (as that would remove :01 resulting to 0:00).

Instead, we can just append a ".000" first and then trim the milliseconds part (which is after the dot .) to the first 3 characters [:3].

import datetime

def milliseconds_to_srt_time(t):
     """Converts the number of milliseconds to HH:MM:SS,ms time"""
     time_str = str(datetime.timedelta(milliseconds=t)) + ".000"
     time_str_split = time_str.split(".", maxsplit=1)
     return f"{time_str_split[0]},{time_str_split[1][:3]}"

print(milliseconds_to_srt_time(8712313))
print(milliseconds_to_srt_time(1000))
print(milliseconds_to_srt_time(1000000))
print(milliseconds_to_srt_time(4000400))
print(milliseconds_to_srt_time(80808231))
print(milliseconds_to_srt_time(80808000))

Output

2:25:12,313
0:00:01,000
0:16:40,000
1:06:40,400
22:26:48,231
22:26:48,000

Upvotes: 1

Related Questions