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

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay