Skip to content
Advertisement

Python function that returns first day and last day from x months ago

The following python code returns the first/last day of prev month but I want to be able to return the first day from 3 months ago instead

from datetime import date, timedelta

last_day_of_prev_month = date.today().replace(day=1) - timedelta(days=1)
start_day_of_prev_month = date.today().replace(day=1) - timedelta(days=last_day_of_prev_month.day)
print("First day of prev month:", start_day_of_prev_month)
print("Last day of prev month:", last_day_of_prev_month)

CURRENT OUTPUT

#First day of prev month: 2021-04-01
#Last day of prev month: 2021-04-30

Advertisement

Answer

You could convert months to weeks:

from datetime import date, timedelta


def get_date_range(month_ago):
    weeks = month_ago * 4
    today = date.today()
    last_day_of_prev_month = today.replace(day=1) - timedelta(days=1)
    past_day = last_day_of_prev_month.replace(day=1) - timedelta(weeks=weeks)
    print("First day of prev month:", last_day_of_prev_month)
    print("Last day of prev month:", past_day.replace(day=1))


get_date_range(3)
get_date_range(6)

Out:

First day of prev month: 2021-04-30
Last day of prev month: 2021-01-01

First day of prev month: 2021-04-30
Last day of prev month: 2020-10-01
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement