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.
Method 1: 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
from datetime import datetime, timedelta
startDate = datetime( 2020 , 1 , 10 )
endDate = datetime( 2020 , 4 , 20 )
addDays = timedelta(days = 31 )
while startDate < = endDate:
print (startDate)
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)
Method 2: rrule
rrule is a package present in dateutil library and this package consists of a method also rrule which takes dtstart, until and specific time period as parameters which are start date, end date, and time period based on iteration respectively. Specific time periods are WEEKLY, MONTHLY, YEARLY, etc.
Note: Use MONTHLY when you want to iterate over months between dates.
Syntax:
rrule(rrule.MONTHLY, dtstart=start_date, until=end_date)
Example:
Iterate over months between dates using rrule.
Python3
from datetime import datetime
from dateutil import rrule
start_date = datetime( 2021 , 1 , 1 )
end_date = datetime( 2022 , 1 , 1 )
for dt in rrule.rrule(rrule.MONTHLY, dtstart = start_date, until = end_date):
print (dt)
|
Output
2021-01-01 00:00:00
2021-02-01 00:00:00
2021-03-01 00:00:00
2021-04-01 00:00:00
2021-05-01 00:00:00
2021-06-01 00:00:00
2021-07-01 00:00:00
2021-08-01 00:00:00
2021-09-01 00:00:00
2021-10-01 00:00:00
2021-11-01 00:00:00
2021-12-01 00:00:00
2022-01-01 00:00:00
Example:
Iterate over years in between dates using rrule.
Python3
from datetime import datetime
from dateutil import rrule
start_date = datetime( 2021 , 1 , 1 )
end_date = datetime( 2022 , 1 , 1 )
for dt in rrule.rrule(rrule.YEARLY, dtstart = start_date, until = end_date):
print (dt)
|
Output
2021-01-01 00:00:00
2022-01-01 00:00:00
Time complexity : O(years), where years is the number of years between start_date and end_date.
Space complexity : O(years), where years is the number of years between start_date and end_date
Last Updated :
28 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...