Sometimes, we want to iterate through a range of dates in Python.
In this article, we’ll look at how to iterate through a range of dates in Python.
How to iterate through a range of dates in Python?
To iterate through a range of dates in Python, we can use a while loop.,
For instance, we write
from datetime import date, timedelta
start_date = date(2020, 1, 1)
end_date = date(2021, 1, 1)
delta = timedelta(days=1)
while start_date <= end_date:
print(start_date.strftime("%Y-%m-%d"))
start_date += delta
to add a while loop that loops from the initial value of start_date
to end_date
by using the start_date <= end_date
condition for the while loop.
In the loop body, we print the current start_date
and then add timedelta
to start_date
at the end of each iterator.
Conclusion
To iterate through a range of dates in Python, we can use a while loop.,