0

How can I convert a number of ms to a date format like : HH/MM/SS/MS

For example, if I have 1900ms, I want to have: 0h 0min 1s 900ms

Thanks in advance for your help!

3 Answers3

2

You can use the timedelta() option from the datetime library. An example of it is:

import datetime

print(str(datetime.timedelta(milliseconds=600000)))

You can also use days, minutes, seconds instead of milliseconds. Link to the official documentation: https://docs.python.org/3/library/datetime.html#datetime.timedelta

veedata
  • 1,048
  • 1
  • 9
  • 15
0

You can use datetime to convert milliseconds in timestamp

import datetime    
datetime.datetime.fromtimestamp(ms/1000.0)
0

Sure - divmod to the rescue:

def ms_to_hmsms(total_ms):
    rest, ms = divmod(int(total_ms), 1000)
    rest, s = divmod(rest, 60)
    rest, m = divmod(rest, 60)
    rest, h = divmod(rest, 60)
    return f"{h}h {m}min {s}s {ms}ms"


print(ms_to_hmsms(1900))
print(ms_to_hmsms(91462322926))

This prints out

0h 0min 1s 900ms
26h 12min 2s 926ms
AKX
  • 152,115
  • 15
  • 115
  • 172