Search code examples
python-3.xtimedata-conversion

How can you convert milliseconds in a format with hours, minutes and seconds in Python? (over 24 hours)


i am having trouble converting milliseconds exerting 24 hours in python. for example, if my input is ms_to_hours(86400000) my result is '0:0:0', i don't want to include days in my calculation. here is my code

def ms_to_hours(millis):
    millis = int(millis)
    seconds = (millis / 1000) % 60
    seconds = int(seconds)
    minutes = (millis / (1000 * 60)) % 60
    minutes = int(minutes)
    hours = (millis / (1000 * 60 * 60)) % 24

    return("%d:%d:%d" % (hours, minutes, seconds))

I need help fixing this to display any milliseconds to (hours, minutes, seconds) even if input exudes 24 hours


Solution

  • You can use the built-in divmod

    def ms_to_hours(millis):
        seconds, milliseconds = divmod(millis, 1000)
        minutes, seconds = divmod(seconds, 60)
        hours, minutes = divmod(minutes, 60)
        return ("%d:%d:%d" % (hours, minutes, seconds))
    
    
    if __name__ == '__main__':
        print(ms_to_hours(88000000))
    

    Output:

    24:26:40