I need to implement the code which will help me to get the list of months between two dates.
I already have the code which will give the month delta , That is the number of months.
Actually, I need the way to achieve getting the list of months between two dates.
Here it is code for getting month delta.
import calendar
import datetime
def calculate_monthdelta(date1, date2):
def is_last_day_of_the_month(date):
days_in_month = calendar.monthrange(date.year, date.month)[1]
return date.day == days_in_month
imaginary_day_2 = 31 if is_last_day_of_the_month(date2) else date2.day
monthdelta = (
(date2.month - date1.month) +
(date2.year - date1.year) * 12 +
(-1 if date1.day > imaginary_day_2 else 0)
)
print monthdelta
return monthdelta
date2 = datetime.datetime.today()
date1 = date2.replace(month=01)
calculate_monthdelta(date1, date2)
Now I need the way to get the list of months between the same.
Any help is appreciated If there is any way to get the list of months between two dates.
Note: Please suggest any idea (If available) apart from the code I have used here.
try this
import datetime
import time
from dateutil.rrule import rrule, MONTHLY
months = [dt.strftime("%m") for dt in rrule(MONTHLY, dtstart=date1, until=date2)]
print months
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With