SyntaxStudy
Sign Up
Python Date Intervals and Ranges
Python Beginner 3 min read

Date Intervals and Ranges

Date Ranges

Generate sequences of dates with pd.date_range() or a simple loop. Check if a date falls within an interval.

Example
from datetime import date, timedelta
import pandas as pd

# Generator
def date_range(start, end):
    current = start
    while current <= end:
        yield current
        current += timedelta(1)

for d in date_range(date(2024, 6, 1), date(2024, 6, 7)):
    print(d)

# Interval check
def in_range(dt, start, end):
    return start <= dt <= end

# Pandas
dates = pd.date_range("2024-Q1", periods=90, freq="D")
Pro Tip

Always use <= inclusive comparisons for intervals — exclusive end dates cause off-by-one bugs.