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
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.
2020-01-10 00:00:00 2020-02-10 00:00:00 2020-03-12 00:00:00 2020-04-12 00:00:00
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.
rrule(rrule.MONTHLY, dtstart=start_date, until=end_date)
Iterate over months between dates using rrule.
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
Iterate over years in between dates using rrule.
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
Please Login to comment...