How to get all dates between two days in Python?

Get all dates between two days in Python

A datetime object can store date and time values in Python. The timedelta object of the datetime module can represent different intervals of time in Python.

We can use this object to get all dates between two days in Python.

To get all dates between two days in Python.

  1. Create two datetime objects.
  2. Use the timedelta object to find the difference between the two days.
  3. Use the for loop to iterate and add one day to the initial date on every iteration.

See the code below.

# Get all dates between two days in Python
from datetime import date, timedelta
# Create two dates
date1 = date(2022, 11, 28) 
date2 = date(2022, 12, 2)
# Use the timedelta object to get all dates between two days in Python
delta = date2-date1
for i in range(delta.days + 1):
    a = date1 + timedelta(days=i)
    print(a)
# Output: 2022-11-28 2022-11-29 2022-11-30 2022-12-01 2022-12-02    

We can also use the rrule object from the dateutil module to get all dates between two days in Python. This object implements the recurrence rules of iCalendar RFC.

The dateutil module provides an extra set of classes and functions that can work with datetime objects

To get all dates between two days in Python.

  1. Create two datetime objects.
  2. Use the rrule object to get the dates between the two days.
  3. Use the for loop to iterate over this object and display the dates.

See the code below.

# Get all dates between two days in Python
from datetime import date
from dateutil.rrule import rrule, DAILY
# Create two dates
date1 = date(2022, 11, 28) 
date2 = date(2022, 12, 2)
# Use the rrule object to get all dates between two days in Python
for i in rrule(DAILY, dtstart=date1, until=date2):
    print(i)
# Output: 2022-11-28 2022-11-29 2022-11-30 2022-12-01 2022-12-02    

To conclude

This article discusses how to get all dates between two days in Python. In the first method, we used the timedelta object to get all the dates. An alternative method using the rrule is also demonstrated.

Explore more from this category at Python Date and Time. Or, search and view other topics at All Tutorials.