How do I calculate number of days between two dates using Python?


In this article we will discuss how to find the number of days between two dates using Python.

We use the datetime module to calculate the number of days between two dates using python.

datetime module

Python has a built-in datetime module that assists us in resolving a number of date-related issues. We just input the two dates with the date type and subtract them to discover the difference between the two dates, which gives us the number of days between the two dates.

Syntax

The syntax of the date() method in datetime module is as follows.

datetime.date(year, month, day)

Parameters

  • year: Takes this parameter as the year.
  • month: Takes this parameter as the month.
  • day: Takes this parameter as the day.

Returns

This function returns date object with same year, month and day. All arguments are required. Arguments may be integers, in the following ranges:

  • MINYEAR <= year <= MAXYEAR
  • 1 <= month <= 12
  • 1 <= day <= number of days in the given month and year

Example

In the following example code, we define the two dates between which we want to find the difference in days. Then subtract these dates to get a timedelta object and examine the day's property of this object to get the required result.

from datetime import date d0 = date(2011, 1, 8) d1 = date(2015, 8, 16) delta = d1 - d0 print('The number of days between the given range of dates is :') print(delta.days)

Output

The output of the above code is as follows.

The number of days between the given range of dates is :
1681

Learn Python with our Python Tutorial.

Updated on: 25-Aug-2023

30K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements