How to use loop and timedelta to Iterate through a range of dates In Python
Timedelta is used to get the dates and loop is to iterate the date from the start date to end date
Syntax: delta = datetime.timedelta(days=1)
Example: Python code to display the dates from 2021 – Feb 1st to 2021 – March 1st
Python3
# import datetime module import datetime # consider the start date as 2021-february 1 st start_date = datetime.date( 2021 , 2 , 1 ) # consider the end date as 2021-march 1 st end_date = datetime.date( 2021 , 3 , 1 ) # delta time delta = datetime.timedelta(days = 1 ) # iterate over range of dates while (start_date < = end_date): print (start_date, end = "\n" ) start_date + = delta |
Output:
2021-02-01 2021-02-02 2021-02-03 2021-02-04 2021-02-05 2021-02-06 2021-02-07 2021-02-08 2021-02-09 2021-02-10 2021-02-11 2021-02-12 2021-02-13 2021-02-14 2021-02-15 2021-02-16 2021-02-17 2021-02-18 2021-02-19 2021-02-20 2021-02-21 2021-02-22 2021-02-23 2021-02-24 2021-02-25 2021-02-26 2021-02-27 2021-02-28 2021-03-01
Python – Iterating through a range of dates
In this article, we will discuss how to iterate DateTime through a range of dates.