Categories
Python Answers

How to find the time difference between two datetime objects in Python?

Spread the love

Sometimes, we want to find the time difference between two datetime objects in Python.

In this article, we’ll look at how to find the time difference between two datetime objects in Python.

How to find the time difference between two datetime objects in Python?

To find the time difference between two datetime objects in Python, we can subtract datetime objects directly.

For instance, we write

import datetime

first_time = datetime.datetime.now()
later_time = datetime.datetime.now()
difference = later_time - first_time
seconds_in_day = 24 * 60 * 60
diff = divmod(difference.days * seconds_in_day + difference.seconds, 60)

to create 2 datetimes first_time and later_time.

Then we get the difference as a timedelta object with

later_time - first_time

Then we us divmod to divide the difference.days * seconds_in_day + difference.seconds by 60 to get the number of minutes and the remainder in seconds in a tuple.

Conclusion

To find the time difference between two datetime objects in Python, we can subtract datetime objects directly.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *