How to calculate the number of days between 2 dates in Python?

February 5, 2021#python

In this article, you will learn how to calculate the number of days between 2 dates in Python.

At the beginning, import date from datetime..

from datetime import date

Then, define the first and second date

first_date = date(2021, 1, 31)
second_date = date(2021, 2, 28)

Then, calculate second_date - first_date

difference = second_date - first_date

At the end, print difference.days

print(difference.days) # 28