user86907
user86907

Reputation: 837

How to calculate the date range of first date and last date of the previous months in python

I am trying to find the first and last date of the previous five months from now using python.

today = datetime.today()
 first = today.replace(day=1)
 lastMonth = first - timedelta(days=153)

Now how do i find the first and last date of each of the previous five months in python?

Can anyone help me with this please?

Upvotes: 0

Views: 545

Answers (1)

PacketLoss
PacketLoss

Reputation: 5746

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')]

Upvotes: 1

Related Questions