Privacy Policy
Snippets index

  elapsed_time():: Human readable time interval between two values of time.time()

import math
import time
import datetime

def elapsed_time(t0, t1, with_milliseconds=False):
    """
    Human readable time interval between two values of time.time()

    Example:
    print("\nElapsed time: %s" % elapsed_time(t0, t1, with_milliseconds=True))
    Elapsed time: 00:00:01.831
    """
    milliseconds, seconds = math.modf(t1 - t0)
    #dt = time.strftime("%H:%M:%S", time.gmtime(seconds))
    dt = "{:0>8}".format(str(datetime.timedelta(seconds=seconds)))
    if with_milliseconds:
        dt += ('%.3f' % milliseconds)[1:]
    return dt

One liner

import time, datetime
t0 = time.time()
...

dt = str(datetime.timedelta(seconds=time.time() - t0))

#or without ms:
dt = str(datetime.timedelta(seconds=t1 - t0)).split('.')[0]

then:

print("\nElapsed time: %s" % dt)
Elapsed time: 0:00:01.831188