How to Get the Time Difference Between 2 Dates in Python



Python


In this article, we show how to get the time difference between 2 dates in Python.

It's very basic.

If you have 2 date objects, or 2 time objects, or 2 datetime objects in Python, you can get the time difference between them simply by subtracting one from the other.

So if I create a date object of April 15,2017 and then create a second date object of April 19, 2017, then all I have to do to get the time difference between them is subtract the first date from the second date. Python automatically creates a timedelta in between them.

We show this in the following code below.



So let's now go over this code.

So the first thing we have to do is import the datetime module. The datetime module allows us to create date objects in Python.

We then create a variable, date1, and set it equal to, datetime.date(2017, 4,15)

This represents the date, April 15, 2017.

We then create a second variable, date2, and set it equal to, datetime.date(2017, 4,19)

We then create a third variable, diff, which is set equal to, diff= date2 -date1

We then print out diff, which is 4 days.

If we had create datetime objects, then there would be a difference in time. But since these are date objects, the timedelta is days.

Just to show that diff is of the timedelta class, we output diff, which you can see is of the timedelta class. We then take the type() o diff, which you can see again is of the datetime.timedelta class.

Again, you can see how Python automatically creates an object of the timedelta class when a mathematical operation is done between 2 objects of the datetime module.

And this is how we get the time difference between 2 dates in Python.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...