How to use Python datetime Module to measure elapsed time in Python In Python

we can also use Python datetime module, we can also record time and find the execution time of a block of code. The process is same as using time.time(), measuring start and end time and then calculating the difference.

Example: How to measure elapsed time using datetime.datetime.now()

Python3




# importing the module
from datetime import datetime
 
 
# sample function for testing
def print_square(x):
    return x ** 2
 
 
# record start time (in datetime format)
start = datetime.now()
 
# calls the function
print_square(3)
 
# record rnd time (in datetime format)
end = datetime.now()
 
# print elapsed time in microseconds
print("Elapsed", (end - start).total_seconds() * 10**6, "µs")


Output:

Elapsed 12.0 µs


How to measure elapsed time in Python?

In Python, we can measure the elapsed time on executing a code segment or a Python script using some built-in Python modules. Here we will cover the usage of time, timeit and datetime module.

Similar Reads

Using Python timeit Module to measure elapsed time in Python

Python timeit module is often used to measure the execution time of small code snippets. We can also use the timeit() function, which executes an anonymous function with a number of executions. It temporarily turns off garbage collection while calculating the time of execution....

Using Python time Module to measure elapsed time in Python

...

Using Python datetime Module to measure elapsed time in Python

...

Contact Us