Search code examples
pythonpython-3.xtimestrftime

Python: How to convert elapsed seconds to H:M:S format


I have this code:

start = time.time()

# some code here that doesn't have anything to do with the question

end = time.time()

time_result = int(end - start)

The time_result variable is the number of seconds it took to finish running the code. How would I convert this to a '00:00:00' string (hours, minutes and seconds)?


Solution

  • IIUC: To convert the number of elapsed seconds to a string such as 00:00:23:

    import time
    from datetime import datetime as dt
    
    start = time.time()
    elapsed = time.time() - start
    
    # Edited to use UTC.
    output = dt.strftime(dt.utcfromtimestamp(elapsed), '%H:%M:%S')
    
    >>> '00:00:23'
    

    Other formatting strings can be found here in the datetime docs.