Search code examples
pythondatetimedatetime-formatpython-datetimepython-3.9

Convert milliseconds to string %H%M%S.%f


I'm trying to convert time in milliseconds to time in a string with milliseconds.

import datetime

x = 23500
j = x / 1000.0
print(datetime.datetime.fromtimestamp(j).strftime('%H:%M:%S.%f'))

The result is '03:00:23.500000'.

And this is not true. 23500 ms is not 3 hours 23 seconds, but only 23 seconds.

The module time allows me correct conversion, but does not display milliseconds.

Can someone explain to me why the datetime module does not give the correct value?

Thanks in advance.


Solution

  • create your timedelta object

    from datetime import timedelta
    
    ms = 23500
    time = timedelta(milliseconds=ms)
    

    now print the result

    print(time) # output: 0:00:02.35
    

    or save the result in a variable

    result = str(time)