Python
DateTime
Date Range
Iteration
Programming Tutorial

Iterating through a range of dates in Python

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

To iterate through a range of dates in Python, use a while loop with timedelta(days=1) to step from a start date to an end date. For a cleaner approach, write a generator function or use pandas.date_range() for DataFrame-oriented workflows. The dateutil.rrule module provides the most flexibility for complex recurrence patterns like "every weekday" or "first Monday of each month".

Method 1: while Loop with timedelta

python
1from datetime import date, timedelta
2
3start_date = date(2024, 1, 1)
4end_date = date(2024, 1, 10)
5
6current = start_date
7while current <= end_date:
8    print(current)
9    current += timedelta(days=1)
10
11# 2024-01-01
12# 2024-01-02
13# ...
14# 2024-01-10

Method 2: Generator Function

A reusable generator is the most Pythonic approach:

python
1from datetime import date, timedelta
2
3def date_range(start, end, step=timedelta(days=1)):
4    current = start
5    while current <= end:
6        yield current
7        current += step
8
9# Daily iteration
10for d in date_range(date(2024, 1, 1), date(2024, 1, 5)):
11    print(d)
12
13# Weekly iteration
14for d in date_range(date(2024, 1, 1), date(2024, 3, 1), timedelta(weeks=1)):
15    print(d)
16
17# Hourly iteration (with datetime)
18from datetime import datetime
19for dt in date_range(datetime(2024, 1, 1), datetime(2024, 1, 1, 12), timedelta(hours=1)):
20    print(dt)

Method 3: List Comprehension with range

python
1from datetime import date, timedelta
2
3start = date(2024, 1, 1)
4end = date(2024, 1, 10)
5num_days = (end - start).days + 1  # inclusive
6
7dates = [start + timedelta(days=i) for i in range(num_days)]
8print(dates)
9# [datetime.date(2024, 1, 1), ..., datetime.date(2024, 1, 10)]

Method 4: pandas.date_range()

python
1import pandas as pd
2
3# Daily range
4dates = pd.date_range(start='2024-01-01', end='2024-01-10', freq='D')
5for d in dates:
6    print(d.date())
7
8# Business days only (Mon-Fri)
9business_days = pd.date_range(start='2024-01-01', end='2024-01-31', freq='B')
10
11# Monthly on the first day
12monthly = pd.date_range(start='2024-01-01', periods=12, freq='MS')
13
14# Common frequency codes:
15# 'D' = daily, 'B' = business day, 'W' = weekly
16# 'MS' = month start, 'ME' = month end
17# 'QS' = quarter start, 'YS' = year start
18# 'h' = hourly, 'min' = minutely

Method 5: dateutil.rrule

python
1from dateutil.rrule import rrule, DAILY, WEEKLY, MONTHLY, MO, FR
2from datetime import date
3
4# Daily
5for d in rrule(DAILY, dtstart=date(2024, 1, 1), until=date(2024, 1, 5)):
6    print(d.date())
7
8# Every Monday and Friday
9for d in rrule(WEEKLY, byweekday=(MO, FR),
10               dtstart=date(2024, 1, 1), until=date(2024, 2, 1)):
11    print(d.date())
12
13# First day of each month
14for d in rrule(MONTHLY, bymonthday=1,
15               dtstart=date(2024, 1, 1), count=6):
16    print(d.date())

Practical Examples

Filtering Dates by Condition

python
1from datetime import date, timedelta
2
3start = date(2024, 1, 1)
4end = date(2024, 1, 31)
5
6# Only weekdays
7weekdays = [
8    start + timedelta(days=i)
9    for i in range((end - start).days + 1)
10    if (start + timedelta(days=i)).weekday() < 5
11]
12print(f"Weekdays in January 2024: {len(weekdays)}")

Processing Files by Date

python
1from datetime import date, timedelta
2
3start = date(2024, 1, 1)
4end = date(2024, 1, 5)
5
6current = start
7while current <= end:
8    filename = f"logs/app-{current.isoformat()}.log"
9    print(f"Processing {filename}")
10    current += timedelta(days=1)
11
12# Processing logs/app-2024-01-01.log
13# Processing logs/app-2024-01-02.log
14# ...

Date Range in Reverse

python
1from datetime import date, timedelta
2
3start = date(2024, 1, 10)
4end = date(2024, 1, 1)
5
6current = start
7while current >= end:
8    print(current)
9    current -= timedelta(days=1)

Common Pitfalls

  • Off-by-one error on the end date: range((end - start).days) excludes the end date. Add + 1 for an inclusive range. Similarly, the while current <= end_date pattern includes the end date, while while current < end_date excludes it.
  • Mixing date and datetime objects: Adding timedelta to a date returns a date, but adding to a datetime returns a datetime. Comparing a date to a datetime raises TypeError in Python 3. Be consistent with which type you use.
  • Using timedelta(months=1) which does not exist: timedelta only supports days, seconds, and microseconds. There is no months or years parameter because months have variable lengths. Use dateutil.relativedelta(months=1) or pandas.DateOffset(months=1) instead.
  • Not handling timezone-aware datetimes: Iterating over naive dates works fine, but mixing naive and timezone-aware datetimes raises errors. If your data is timezone-aware, ensure the start and end dates use the same timezone.
  • Creating a huge list of dates in memory: For very large ranges (millions of days), a list comprehension stores all dates in memory at once. Use a generator function with yield to iterate lazily without memory overhead.

Summary

  • Use while loop + timedelta(days=1) for simple date iteration
  • Write a generator function with yield for a reusable, memory-efficient date range
  • Use pandas.date_range() for business days, monthly, quarterly, and other complex frequencies
  • Use dateutil.rrule for recurrence patterns like "every Monday and Friday"
  • Use dateutil.relativedelta instead of timedelta when you need month or year increments

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.