How to get the difference between two dates in Python?

Sometimes, we want to get the difference between two dates in Python.

In this article, we’ll look at how to get the difference between two dates in Python.

How to get the difference between two dates in Python?

To get the difference between two dates in Python, we can subtract the 2 datetimes directly.

For instance, we write

from datetime import datetime

def days_between(d1, d2):
    d1 = datetime.strptime(d1, "%Y-%m-%d")
    d2 = datetime.strptime(d2, "%Y-%m-%d")
    return abs((d2 - d1).days)

to call strptime to convert the date strings d1 and d2 into datetime objects.

Then we subtract the 2 datetime objects with -.

Then we get the days difference between them with days.

And we return the absolute value of the difference with abs.

Conclusion

To get the difference between two dates in Python, we can subtract the 2 datetimes directly.