1

I need some help with finding the last saturday of current month in Python. Now, this code run today show me Saturday 31th July, but I want to obtain Saturday 28th August.

off= (date.today().weekday() - 5)%7
Last_Saturday = (date.today() - timedelta(days=off)).strftime("%d/%m/%Y")
Azsb
  • 35
  • 5
  • 2
    Does this answer your question? [How to get the last day of the month?](https://stackoverflow.com/questions/42950/how-to-get-the-last-day-of-the-month) – quamrana Aug 04 '21 at 13:01
  • @quamrana hmm I look for the way for last Saturday of month – Azsb Aug 04 '21 at 13:04

3 Answers3

0

Adapted from this question: Python: get last Monday of July 2010

You could do this to get the day of the month number, then do whatever you want with that

from datetime import datetime
import calendar

month = calendar.monthcalendar(datetime.now().year, datetime.now().month)
day_of_month = max(month[-1][calendar.SATURDAY], month[-2][calendar.SATURDAY])
Ben
  • 460
  • 5
  • 18
0

Using @quamrana answer you could do the following

import calendar
if calendar.monthcalendar(2021, 8)[-1][5] != 0:
    print(calendar.monthcalendar(2021, 8)[-1][5])
else:
    print(calendar.monthcalendar(2021, 8)[-2][5])

Output

>>> if calendar.monthcalendar(2021, 8)[-1][5] != 0:
...     print(calendar.monthcalendar(2021, 8)[-1][5])
... else:
...     print(calendar.monthcalendar(2021, 8)[-2][5])
... 
28
>>> 
Welyweloo
  • 88
  • 8
0

In whatever month we are, you can use this code to get the date corresponding to the last Saturday.
Note that I considered only the last week of the month.
Inspiration came from Percentage of Wednesdays ending months in the 21st Century

from datetime import date, datetime
import calendar as cal

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


length_month = cal.monthrange(year, month)[1]
for day in range(length_month,length_month-7,-1):
  if datetime(year, month, day).weekday()==5:
    last_saturday = datetime(year, month, day).strftime("%d/%m/%Y")

print(f'Last Saturday of the current month : {last_saturday}')
tem
  • 101
  • 4