Iterating through a range of dates in Python
Data Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.
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
Method 2: Generator Function
A reusable generator is the most Pythonic approach:
Method 3: List Comprehension with range
Method 4: pandas.date_range()
Method 5: dateutil.rrule
Practical Examples
Filtering Dates by Condition
Processing Files by Date
Date Range in Reverse
Common Pitfalls
- Off-by-one error on the end date:
range((end - start).days)excludes the end date. Add+ 1for an inclusive range. Similarly, thewhile current <= end_datepattern includes the end date, whilewhile current < end_dateexcludes it. - Mixing
dateanddatetimeobjects: Addingtimedeltato adatereturns adate, but adding to adatetimereturns adatetime. Comparing adateto adatetimeraisesTypeErrorin Python 3. Be consistent with which type you use. - Using
timedelta(months=1)which does not exist:timedeltaonly supports days, seconds, and microseconds. There is nomonthsoryearsparameter because months have variable lengths. Usedateutil.relativedelta(months=1)orpandas.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
yieldto iterate lazily without memory overhead.
Summary
- Use
whileloop +timedelta(days=1)for simple date iteration - Write a generator function with
yieldfor a reusable, memory-efficient date range - Use
pandas.date_range()for business days, monthly, quarterly, and other complex frequencies - Use
dateutil.rrulefor recurrence patterns like "every Monday and Friday" - Use
dateutil.relativedeltainstead oftimedeltawhen you need month or year increments
Related reading
- Iterating through directories with Python
- Java Virtual Machine vs. Python Interpreter parlance?
- Java Virtual Machine vs. Python Interpreter parlance?
- Java's Mahout equivalent in Python
- Javascript equivalent of Python's zip function
- joblib.load __main__ AttributeError
- Join a string using delimiters
- join list of lists in python
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo course covers this one yet
Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.
Build my courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.