Categories
Python Answers

How to iterate through a range of dates in Python?

Spread the love

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 the datetime module and a while loop.

For instance, we write:

from datetime import date, timedelta

start_date = date(2021, 1, 1)
end_date = date(2021, 2, 1)
delta = timedelta(days=1)
while start_date <= end_date:
    print(start_date.strftime("%Y-%m-%d"))
    start_date += delta

We create the start_date and end_date objects with the date function.

Then we call timedelta with the magnitude of the time difference we want to increment by.

Next, we use a while loop to loop through the dates and print the dates as strings with striftime.

And then we update start_date by adding timedelta to it.

Therefore, we get:

2021-01-01
2021-01-02
2021-01-03
2021-01-04
2021-01-05
2021-01-06
2021-01-07
2021-01-08
2021-01-09
2021-01-10
2021-01-11
2021-01-12
2021-01-13
2021-01-14
2021-01-15
2021-01-16
2021-01-17
2021-01-18
2021-01-19
2021-01-20
2021-01-21
2021-01-22
2021-01-23
2021-01-24
2021-01-25
2021-01-26
2021-01-27
2021-01-28
2021-01-29
2021-01-30
2021-01-31
2021-02-01

printed.

Conclusion

To iterate through a range of dates in Python, we can use the datetime module and a while loop.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *