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.
Advertisement
Answer
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)