The below is based off an two answers already on SO. It adds in the ability to respond with the first and last day over a range of dates.
Get year month for last X months
How to get the first and last day of the month
import calendar
import datetime
from dateutil.relativedelta import relativedelta
def get_last_months(start_date, months):
for i in range(months):
_, num_days = calendar.monthrange(start_date.year,start_date.month)
first_day = datetime.date(start_date.year, start_date.month, 1).strftime('%Y-%m-%d')
last_day = datetime.date(start_date.year, start_date.month, num_days).strftime('%Y-%m-%d')
yield (first_day, last_day)
start_date += relativedelta(months = -1)
months_back = 5
print([i for i in get_last_months(datetime.datetime.today(), months_back)])
Output:
[('2020-10-01', '2020-10-31'), ('2020-09-01', '2020-09-30'), ('2020-08-01', '2020-08-31'), ('2020-07-01', '2020-07-31'), ('2020-06-01', '2020-06-30')]