In this article, we will discuss how to iterate DateTime through a range of dates.
Using loop and timedelta to Iterate through a range of dates
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
start_date = datetime.date( 2021 , 2 , 1 )
end_date = datetime.date( 2021 , 3 , 1 )
delta = datetime.timedelta(days = 1 )
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
Using the dateutil library to Iterate through a range of dates
Here we are using the dateutil built-in library of Python to iterate through the given range of dates.
Syntax: rrule( frequency )
Where frequency can be DAILY/MONTHLY/ANNUALLY.
Example:
Python3
from datetime import date
from dateutil.rrule import rrule, DAILY
start_date = date( 2022 , 9 , 1 )
end_date = date( 2022 , 9 , 11 )
for d in rrule(DAILY, dtstart = start_date, until = end_date):
print (d.strftime( "%Y-%m-%d" ))
|
Output:
2022-09-01
2022-09-02
2022-09-03
2022-09-04
2022-09-05
2022-09-06
2022-09-07
2022-09-08
2022-09-09
2022-09-10
2022-09-11
Using pandas to Iterate through a range of dates
We can use the date_range() function method that is available in pandas. It is used to return a fixed frequency DatetimeIndex.
Syntax: pandas.date_range(start, end)
Parameter:
- start is the starting date
- end is the ending date
We can iterate to get the date using date() function.
Example:
Python3
import pandas as pd
a = pd.date_range(start = '1/1/2021' , end = '2/1/2021' )
for i in a:
print (i.date())
|
Output:
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
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!