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
# import necessary packages from datetime import datetime from dateutil import rrule # dates 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) |
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
# import necessary packages from datetime import datetime from dateutil import rrule # dates 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) |
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
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.