Python program to find number of days between two given dates
Last Updated :
19 Jul, 2023
Given two dates, Write a Python program to find the total number of days between them.
Examples:
Input : dt1 = 13/12/2018, dt2 = 25/2/2019
Output : 74 daysInput : dt1 = 01/01/2004, dt2 = 01/01/2005
Output : 366 days
Naive Approach: One Naive Solution is to start from dt1 and keep counting the days till dt2 is reached. This solution requires more than O(1) time.
A Better and Simple solution is to count the total number of days before dt1 from i.e., total days from 00/00/0000 to dt1, then count the total number of days before dt2. Finally, return the difference between the two counts.
Python3
# Python3 program two find number of
# days between two given dates
# A date has day 'd', month 'm' and year 'y'
class Date:
def __init__(self, d, m, y):
self.d = d
self.m = m
self.y = y
# To store number of days in all months from
# January to Dec.
monthDays = [31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31]
# This function counts number of leap years
# before the given date
def countLeapYears(d):
years = d.y
# Check if the current year needs to be considered
# for the count of leap years or not
if (d.m <= 2):
years -= 1
# An year is a leap year if it is a multiple of 4,
# multiple of 400 and not a multiple of 100.
return int(years / 4) - int(years / 100) + int(years / 400)
# This function returns number of days between two
# given dates
def getDifference(dt1, dt2):
# COUNT TOTAL NUMBER OF DAYS BEFORE FIRST DATE 'dt1'
# initialize count using years and day
n1 = dt1.y * 365 + dt1.d
# Add days for months in given date
for i in range(0, dt1.m - 1):
n1 += monthDays[i]
# Since every leap year is of 366 days,
# Add a day for every leap year
n1 += countLeapYears(dt1)
# SIMILARLY, COUNT TOTAL NUMBER OF DAYS BEFORE 'dt2'
n2 = dt2.y * 365 + dt2.d
for i in range(0, dt2.m - 1):
n2 += monthDays[i]
n2 += countLeapYears(dt2)
# return difference between two counts
return (n2 - n1)
# Driver program
dt1 = Date(13, 12, 2018)
dt2 = Date(25, 2, 2019)
print(getDifference(dt1, dt2), "days")
Time Complexity: O(1)
Auxiliary Space: O(1)
Using Python datetime module:
Python comes with an inbuilt datetime module that helps us to solve various datetime related problems. In order to find the difference between two dates we simply input the two dates with date type and subtract them, which in turn provides us the number of days between the two dates.
Python3
# Python3 program to find number of days
# between two given dates
from datetime import date
def numOfDays(date1, date2):
#check which date is greater to avoid days output in -ve number
if date2 > date1:
return (date2-date1).days
else:
return (date1-date2).days
# Driver program
date1 = date(2018, 12, 13)
date2 = date(2015, 2, 25)
print(numOfDays(date1, date2), "days")
Time Complexity: O(1)
Auxiliary Space: O(1)
One approach is to use the dateutil library, which provides a more convenient and flexible way of handling dates and times in Python. To install dateutil, you can use the following command:
pip install python-dateutil
To find the number of days between two dates using dateutil, you can use the rdelta function from the relativedelta module, as shown in the example below:
Python3
from dateutil import relativedelta
from datetime import datetime
# Parse the dates from strings into datetime objects
date1 = datetime.strptime("13/10/2018", "%d/%m/%Y")
date2 = datetime.strptime("25/12/2018", "%d/%m/%Y")
# Calculate the difference between the two dates
difference = relativedelta.relativedelta(date2, date1)
# Print the number of days between the two dates
print(difference.months, "months", difference.days, "days")
# This code is contributed by Edula Vinay Kumar Reddy
Time Complexity: O(1)
Auxiliary Space: O(1)
Method#4: Using time module
Approach
this approach uses the date library in Python to convert the input strings to date objects, then calculates the difference between the two dates using the timedelta function, and finally returns the number of days in the timedelta object.
Algorithm
1. Convert the input strings to timestamp using time.mktime() method
2. Calculate the difference between the two timestamps
3. Convert the difference to days by dividing it with the number of seconds in a day (86400)
4. Return the number of days as integer
Python3
import time
def days_between_dates(dt1, dt2):
date_format = "%d/%m/%Y"
a = time.mktime(time.strptime(dt1, date_format))
b = time.mktime(time.strptime(dt2, date_format))
delta = b - a
return int(delta / 86400)
dt1 = "13/12/2018"
dt2 = "25/2/2019"
print(days_between_dates(dt1, dt2))
Time Complexity: O(1) (time operations take constant time)
Space Complexity: O(1) (no extra data structures used)
Method#5: Using reduce from functools:
Algorithm:
- Import the required modules date from datetime and reduce from functools.
- Define a function numOfDays that takes two arguments date1 and date2.
- The function uses reduce to apply a lambda function to a list [date1, date2].
- The lambda function takes two arguments x and y and calculates the number of days between the two dates y-x.
- The final result is the number of days between date1 and date2.
- Assign date(2018, 12, 13) to date1 and date(2019, 2, 25) to date2.
- Call numOfDays function with date1 and date2 as arguments.
- Print the result along with the string "days".
Python3
from datetime import date
from functools import reduce
def numOfDays(date1, date2):
return reduce(lambda x, y: (y-x).days, [date1, date2])
date1 = date(2018, 12, 13)
date2 = date(2019, 2, 25)
print(numOfDays(date1, date2), "days")
# This code is contributed by Jyothi pinjala
Time complexity: O(n), where n is the number of dates between date1 and date2. In this case, since there are only two dates, the time complexity is constant.
Auxiliary Space: O(1). The function uses a constant amount of memory regardless of the size of the input dates.
Similar Reads
Python program to find day of the week for a given date
Write a Python program to extract weekdays from a given date for any particular date in the past or future. Let the input be in the format "dd mm yyyy". Example Input : 03 02 1997 Output : MondayInput : 31 01 2019Output : ThursdayThe already discussed approach to extract weekdays from a given date f
6 min read
Python Program to Get total Business days between two dates
Given two dates, our task is to write a Python program to get total business days, i.e weekdays between the two dates. Example: Input : test_date1, test_date2 = datetime(2015, 6, 3), datetime(2015, 7, 1) Output : 20 Explanation : Total weekdays, i.e business days are 20 in span. Input : test_date1,
6 min read
Python - Generate k random dates between two other dates
Given two dates, the task is to write a Python program to get K dates randomly. Input : test_date1, test_date2 = date(2015, 6, 3), date(2015, 7, 1), K = 7 Output : [datetime.date(2015, 6, 18), datetime.date(2015, 6, 25), datetime.date(2015, 6, 29), datetime.date(2015, 6, 11), datetime.date(2015, 6,
4 min read
Python program to find the first day of given year
Given a year as input, write a Python to find the starting day of the given year. We will use the Python datetime library in order to solve this problem. Example: Input : 2010 Output :FridayInput :2019 Output :Tuesday Below is the implementation: Python3 # Python program to find the first day of giv
2 min read
Python Program to Display Calendar of a Given Month
Displaying a calendar for a given month is a common task in programming, and Python provides several methods to achieve this. In this article, we will explore different approaches to creating a Python program that displays the calendar of a specified month. Whether using built-in libraries or third-
4 min read
Python program to find Last date of Month
Given a datetime object, the task is to write a Python Program to compute the last date of datetime object Month. Examples: Input : test_date = datetime.datetime(2018, 6, 4) Output : 30 Explanation : April has 30 days, each year Input : test_date = datetime.datetime(2020, 2, 4) Output : 29 Explanati
3 min read
Python program to find difference between current time and given time
Given two times h1:m1 and h2:m2 denoting hours and minutes in 24 hours clock format. The current clock time is given by h1:m1. The task is to calculate the difference between two times in minutes and print the difference between two times in h:m format. Examples:Input : h1=7, m1=20, h2=9, m2=45 Outp
2 min read
Python - Convert day number to date in particular year
Given day number, convert to date it refers to. Input : day_num = "339", year = "2020" Output : 12-04-2020 Explanation : 339th Day of 2020 is 4th December. Input : day_num = "4", year = "2020" Output : 01-04-2020 Explanation : 4th Day of 2020 is 4th January. Method #1 : Using datetime.strptime() In
5 min read
Python program to get the nth weekday after a given date
Given a date and weekday index, the task is to write a Python program to get the date for the given day of the week occurring after the given date. The weekday index is based on the below table: IndexWeekday0Monday1Tuesday2Wednesday3Thursday4Friday5Saturday6Sunday Examples: Input : test_date = datet
3 min read
Python program to find birthdate on the same day you were born
Write a program to find birthdates till a given year on the same day you were born. Let the input be of the format: YYYY-MM-DDExamples:Input: 1996-11-12 Output: ['1996-11-12', '2002-11-12', '2013-11-12', '2019-11-12', '2024-11-12', '2030-11-12', '2041-11-12', '2047-11-12'] Input: 1992-11-2 Output: [
3 min read