0

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
Girl007
  • 165
  • 1
  • 13
  • I have replaced days= 90 but I got 2021-01-31 for the last day of the prev month instead wheras I want it to be 2021-04-30 just want the first day to change sorry if i didnt make that clear will update question @sayse – Girl007 May 12 '21 at 10:51
  • oh sorry yes I have this is in terms of 30 days, 90 days etc – Girl007 May 12 '21 at 10:54
  • [Return datetime object of previous month](https://stackoverflow.com/q/3424899/1324033) – Sayse May 12 '21 at 10:55

1 Answers1

1

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
Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47