What is a good way to get rid of these if/elif/else inside the for loop? How you would improve readability of it?
from datetime import datetime
from calendar import monthrange
def iter_completed_months(initial_date, today):
delta_months_years = (today.year - initial_date.year)*12
delta_months_current_year = today.month - initial_date.month
return delta_months_years + delta_months_current_year
initial_date = datetime(2021, 11, 30)
today = datetime.now()
# populate a list that goes from initial_date until today with all the dates
# representing the very end of each month
year = initial_date.year
month = initial_date.month
end_month_dates = []
for _iter_month in range(iter_completed_months(initial_date, today)):
if month <= 12:
day = monthrange(year, month)[1]
elif month > 12:
year = year + 1
month = 1
day = monthrange(year, month)[1]
else:
day = monthrange(year, month)[1]
end_month_dates.append(datetime(year, month, day))
month = month + 1
print(end_month_dates)
this code populates a list end_month_dates with all "end of months" from initial_date to today.