Jaime López
Data Product Developer
Centereach, NY

Sections:

Profiles:

Loop between dates in Python

Sometimes is necessary iterate between two dates, going day by day. Here is a snippet that uses a loop to generate the list of dates contained in a given interval of time.

import datetime

# Given dates to iterate between them
start_stamp = '2023-01-01'
end_stamp = '2023-01-20'

# Converting to date type
start_date = datetime.date.fromisoformat(start_stamp)
end_date = datetime.date.fromisoformat(end_stamp)

# Defining a delta of 1 day to be use a the loop step
delta = datetime.timedelta(days=1)

# The loop with a variable to keep the list of dates
result = []
pos = start_date
while pos <= end_date:
    result.append(pos)
    pos += delta

# Output
for mark in result:
    print(mark)

The period is given by start_stamp and end_stamp. They are converted to date type. Then, a step of one day is defined. After that, the loop is made starting on the initial date, adding one day in each step, until the final date is reached.

Whith the same logic, a more compact solution for the loop may be:

days = (end_date - start_date).days + 1
result = [start_date + datetime.timedelta(days=x)
    for x in range(days)]

Date: 2023-02-24
Updated: 2023-03-11