Sling Academy
Home/Python/Python: Get a list of all dates between 2 dates (3 ways)

Python: Get a list of all dates between 2 dates (3 ways)

Last updated: June 18, 2023

When working with Python, there might be cases where you want to get a list of all dates between 2 given dates, such as when extracting data from a dataset or when working on applications that involve scheduling or planning.

This concise, example-based article will show you a couple of different ways to retrieve a list of dates between 2 other dates. We’ll only use built-in features of Python and won’t rely on any external libraries. Without more delay, let’s move on to the main points.

Using list comprehension and the timedelta() function

This approach is simple and efficient. The steps are:

  1. Use a list comprehension to iterate over the range of days between the start and end date using the timedelta() function.
  2. Generate each date by adding the current day offset to the start date.
  3. Return the list of dates.

Code example:

from datetime import timedelta, date

# Function to get dates between two dates (including start and end dates)
def get_dates_between(start_date, end_date):
    return [start_date + timedelta(days=i) 
            for i in range((end_date - start_date).days + 1)]

start_date = date(2024, 1, 5)
end_date = date(2024, 1, 10)

dates_between = get_dates_between(start_date, end_date)
print(dates_between)

Output:

[datetime.date(2024, 1, 5), 
 datetime.date(2024, 1, 6), 
 datetime.date(2024, 1, 7), 
 datetime.date(2024, 1, 8), 
 datetime.date(2024, 1, 9), 
 datetime.date(2024, 1, 10)]

In case you want to exclude the start and end dates from the result list, change the get_dates_between function in the code snippet above like this:

def get_dates_between(start_date, end_date):
    return [start_date + timedelta(days=i) 
            for i in range(1, (end_date - start_date).days)]

Using a generator function

This approach is great for large date ranges as it generates dates on-the-fly. It uses a generator function to yield each date between the start and end dates. It provides an efficient way to generate and iterate over the dates without creating the entire list upfront.

Step-by-step explanation:

  1. Define a generator function that takes the start and end dates as parameters.
  2. Use a loop and timedelta() to yield each date between the start and end dates.
  3. Call the generator function and iterate over the generated dates using a loop or any desired iteration method.

Code example:

from datetime import timedelta, date

# define a generator function to generate dates between two dates 
# including both boundaries
def generate_dates(start_date, end_date):
    current_date = start_date
    while current_date <= end_date:
        yield current_date
        current_date += timedelta(days=1)

start_date = date(2023, 11, 29)
end_date = date(2023, 12, 3)

dates = list(generate_dates(start_date, end_date))
print(dates)

Output:

[datetime.date(2023, 11, 29), datetime.date(2023, 11, 30), datetime.date(2023, 12, 1), datetime.date(2023, 12, 2), datetime.date(2023, 12, 3)]

To remove the start and end dates from the result, you can change the generate_dates function to this:

def generate_dates(start_date, end_date):
    current_date = start_date + timedelta(days=1)
    while current_date < end_date:
        yield current_date
        current_date += timedelta(days=1)

Using a for loop and the timedelta() function

This technique consists of the following steps:

  1. Initialize an empty list to store the dates.
  2. Start a loop from the start date to the end date (inclusive) using the timedelta function to increment the date by one day in each iteration.
  3. Append each date to the list with the list.append() method.
  4. Return the list of dates.

Example:

from datetime import timedelta, date

# this function returns a list of dates between two dates (inclusive)
def get_dates_between(start_date, end_date):
    dates = []
    current_date = start_date
    while current_date <= end_date:
        dates.append(current_date)
        current_date += timedelta(days=1)
    return dates

start_date = date(2024, 2, 27)
end_date = date(2024, 3, 2)

dates_between = get_dates_between(start_date, end_date)
print(dates_between)

Output:

[datetime.date(2024, 2, 27), datetime.date(2024, 2, 28), datetime.date(2024, 2, 29), datetime.date(2024, 3, 1), datetime.date(2024, 3, 2)]

As always, the get_dates_between function can be modified to exclude the boundaries from the result:

def get_dates_between_exclusive(start_date, end_date):
    dates = []
    current_date = start_date + timedelta(days=1)
    while current_date < end_date:
        dates.append(current_date)
        current_date += timedelta(days=1)
    return dates

That’s it.

Next Article: Python: How to subtract/add a duration to a timestamp

Previous Article: Python: Get the Current Date and Time with Timezone

Series: Date and Time in Python

Python

You May Also Like

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots