;

How to Get or Find the Number of Days Between Two Given Dates in Python


Tutorialsrack 29/03/2020 Programs Python

In this article, we will learn how to get or find the number of days between two given dates in python.

Example 1: In this example,  we have two date objects, we can subtract one from the other and query the resulting timedelta object for the number of days.

Example 1
#Import Module
from datetime import date

date0 = date(2020, 1, 1)
date1 = date(2021, 1, 1)
num_of_days_diff = date1 - date0
print("\nTotal Number of Days Between Two Dates: ",num_of_days_diff.days)
# Output ==> Total Number of Days Between Two Dates:  366

Example 2: In this example, we will use a datetime.toordinal() method, which returns the proleptic Gregorian ordinal of the date, where January 1 of year 1 has ordinal 1. For any date object d, date.fromordinal(d.toordinal()) == d. It seems well suited for calculating days difference, though not as readable as timedelta.days.

Example 2
#Import Module
import datetime

date0 = date(2020, 1, 1)
date1 = date(2021, 1, 1)
num_of_days_diff = date1.toordinal() - date0.toordinal()
print("\nTotal Number of Days Between Two Dates: ",num_of_days_diff)
# Output ==> Total Number of Days Between Two Dates:  366

I hope this article will help you to understand how to get or find the number of days between two given dates in python.

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags