Iteration using timedelta

timedelta() is used for calculating differences in dates and also can be used for date manipulations in Python

Example:

But using timedelta we can’t iterate over months between dates perfectly because here we are adding 31 days for each month. But every month won’t have exact 31 days. Some months have 30 and even 28, 29. In order to solve the problem rrule comes into the act that helps to iterate between dates by a specific period of time.

Code

Python3




# import necessary packages
from datetime import datetime, timedelta
 
# date initialisation
startDate = datetime(2020, 1, 10)
endDate = datetime(2020, 4, 20)
 
# stores 31 days that can be added
addDays = timedelta(days=31)
 
while startDate <= endDate:
    print(startDate)
    # add a month
    startDate += addDays


Output

2020-01-10 00:00:00
2020-02-10 00:00:00
2020-03-12 00:00:00
2020-04-12 00:00:00

Time complexity:O(1)

Space complexity:O(1)

How to Iterate over months between two dates in Python?

In this article, we will discuss how to iterate over months between two dates using Python. 

We can iterate over months between two dates using timedelta and rrule methods.

Similar Reads

Method 1: Iteration using timedelta

timedelta() is used for calculating differences in dates and also can be used for date manipulations in Python...

Method 2: rrule

...