This post describes a recipe for generating a range of dates in Python (no dependencies - just standard library).
Generating range of dates
Let’s say you have two dates: 2024-02-01 (start date) and 2024-02-15 (end date). You need to generate a range of dates between these two.
Python does not have any builtin function/object that which specifically generates a range of dates. However, you can easily do it yourself by using datetime.date
, datetime.timedelta
objects along with looping.
Let’s take a look at code:
from datetime import date, timedelta
start_date = date(2024, 2, 1)
end_date = date(2024, 2, 5)
days_diff = (end_date - start_date).days
range_of_dates = [
start_date + timedelta(days=i)
for i in range(days_diff + 1)
]
print(range_of_dates)
Executing above snippet would produce following results:
[
date(2024, 2, 1),
date(2024, 2, 2),
date(2024, 2, 3),
date(2024, 2, 4),
date(2024, 2, 5)
]
We start with calculating the difference in days between end and start date. Subtracting two dates returns a timedelta and we access .days
property which an integer.
Then we construct a list comprehension that iterates over days difference. If you want to get inclusive range, then days_diff
should be increased by 1 - otherwise just iterate over days_diff
to get an exclusive range.
Summing a date and timedelta object results in a new date object (increased or decreased by the timedelta value). We use this fact in our comprehension expression - each iteration produces a new date (next day).
If you want to keep it in one line, that’s fine:
range_of_dates = [
start_date + timedelta(days=i)
for i in range((end_date - start_date).days + 1)
]
(11/52) This is a 11th post from my blogging challenge (publishing 52 posts in 2024).