Write a Python program to get a list of dates between two dates


This program generates a date range between two given dates and prints each date in the range in the format of "dd-mm-yyyy". The program uses the datetime module to work with dates and timedelta to calculate the difference between two dates. It defines a function daterange that takes two dates as inputs and returns a generator that yields all the dates between those two dates, including the start and end dates.

In the main part of the program, two date objects are created using the date() constructor. These dates represent the start and end dates of the date range to be generated. The daterange() function is then called with the start and end dates as inputs, and the resulting generator is used in a for loop to iterate over all the dates in the range. Finally, each date is printed using the strftime() method to format the date in the desired format of "dd-mm-yyyy".

Source Code

from datetime import timedelta, date
 
def daterange(d1, d2):
    for n in range(int ((d2 - d1).days)+1):
        yield d1 + timedelta(n)
 
sdate = date(2022, 1, 10)
edate = date(2022, 1, 21)
for dt in daterange(sdate, edate):
    print(dt.strftime("%d-%m-%Y"))

Output

10-01-2022
11-01-2022
12-01-2022
13-01-2022
14-01-2022
15-01-2022
16-01-2022
17-01-2022
18-01-2022
19-01-2022
20-01-2022
21-01-2022

Example Programs