The piece of code below prints the days contained in each month between the dates d0
and d1
.
It prints the days between d0
and end of d0
months. It then prints the days in each of the following months until it reaches d1
month. At that point, it just prints the day of the d1
date.
In this case, datetime
and dateutil.relativedelta
are used to handle datetime objects and month increases.
from datetime import date
from dateutil.relativedelta import *
d0 = date(2008, 8, 18)
d1 = date(2009, 9, 26)
def days_in_month(month, year):
if month == 12:
return (date(year+1, 1, 1) - date(year, month, 1)).days
return (date(year, month+1, 1) - date(year, month, 1)).days
def get_month_year_string(date):
return date.strftime("%B %Y")
d = d0
while d.month < d1.month or d.year < d1.year:
days_to_end_month = days_in_month(d.month, d.year)
if d == d0:
days_to_end_month -= d0.day
print(f'{get_month_year_string(d)}: {days_to_end_month} days')
d = d + relativedelta(months=+1)
print(f'{get_month_year_string(d1)}: {d1.day} days')
# Output:
# August 2008: 13 days
# September 2008: 30 days
# October 2008: 31 days
# November 2008: 30 days
# December 2008: 31 days
# January 2009: 31 days
# February 2009: 28 days
# March 2009: 31 days
# April 2009: 30 days
# May 2009: 31 days
# June 2009: 30 days
# July 2009: 31 days
# August 2009: 31 days
# September 2009: 26 days