Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last friday of each month in python

I want last friday of each month for upcoming three months.

Friday_date = datetime.date.today()

    while Friday_date.weekday() != 4:
        Friday_date += datetime.timedelta(1)

This gives me the nearest friday. I want to make sure this is the last friday of this month so that i can add 28 days to get next friday.

like image 894
Madan Raj Avatar asked Nov 26 '25 12:11

Madan Raj


2 Answers

The easiest way to do this is to use the module dateutil:

>>> from dateutil.relativedelta import FR, relativedelta
>>> datetime.date.today()+relativedelta(day=31, weekday=FR(-1))
datetime.date(2021, 6, 25)

Don't assume you can get the last Friday of subsequent months just by adding 28 days. It won't always work. Adding 28 days to the last Friday of February 2024 gives you this:

>>> datetime.date(2024,2,1)+relativedelta(day=31, weekday=FR(-1), days=28)
datetime.date(2024, 3, 22)

but the last Friday of that month is 29 March. Let dateutil do that correctly for you:

>>> datetime.date(2024,2,1)+relativedelta(day=31, weekday=FR(-1), months=1)
datetime.date(2024, 3, 29)
like image 158
BoarGules Avatar answered Nov 29 '25 01:11

BoarGules


If needed with standard library only, here is with calendar and datetime:

import calendar
from datetime import date

today = date.today()
year, month = today.year, today.month

n_months = 4
friday = calendar.FRIDAY

for _ in range(n_months):
    # get last friday
    c = calendar.monthcalendar(year, month)
    day_number = c[-1][friday] or c[-2][friday]

    # display the found date
    print(date(year, month, day_number))

    # refine year and month
    if month < 12:
        month += 1
    else:
        month = 1
        year += 1

where the line c[-1][friday] or c[-2][friday] first checks the last week of the month: is Friday nonzero there? if so take it, else look at the week before where there must be a Friday.

This prints

2021-06-25
2021-07-30
2021-08-27
2021-09-24
like image 22
Mustafa Aydın Avatar answered Nov 29 '25 02:11

Mustafa Aydın



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!