DEV Community

Murtaja Ziad
Murtaja Ziad

Posted on • Originally published at blog.murtajaziad.xyz on

How to calculate the number of days between 2 dates in 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
Enter fullscreen mode Exit fullscreen mode

Then, define the first and second date

first_date = date(2021, 1, 31)
second_date = date(2021, 2, 28)
Enter fullscreen mode Exit fullscreen mode

Then, calculate second_date - first_date

difference = second_date - first_date
Enter fullscreen mode Exit fullscreen mode

At the end, print difference.days

print(difference.days) # 28
Enter fullscreen mode Exit fullscreen mode

Discussion (0)