How do I get the last Monday (or other day) of a given month?
Asked
Active
Viewed 4,449 times
4
-
all I can think of is to iterate through every day of the month (descending) and asking if it's Monday. I was hoping for something simpler and shorter. – user984003 Oct 09 '12 at 09:04
-
3Well, actually that is quite a good approach. However there is no need for iteration, you can use substraction. If the last day of the month (`lom`) is Wednesday (use `weekday()`), then you know that the Monday will be last day `lom - 2`. I am sure you can generalise upon that. – Hans Then Oct 09 '12 at 09:11
4 Answers
8
Using the calendar module from the stdlib:
import calendar
cal = calendar.Calendar(0)
month = cal.monthdatescalendar(2010, 7)
lastweek = month[-1]
monday = lastweek[0]
print(monday)
2010-07-26

Gary van der Merwe
- 9,134
- 3
- 49
- 80
-
3Unfortunately, this does not work for all cases. `lastweek` is a complete week (with first days of the following month if applicable), which for "last Sunday in July 2010" returns "2010-08-01". Try `lastweek[6]` – eumiro Oct 09 '12 at 10:39
-
1@eumiro you are correct. One can give the day that your are looking for as the first day of week, so that you can always do lastweek[0], but that is messy. I think your dateutil answer is better. – Gary van der Merwe Oct 09 '12 at 11:16
-
this function fails in some cases, e.g. try getting last Friday of May, 2016, or last Wednesday of February, 2016 using this function – ierdna Mar 19 '16 at 01:29
-
I reckon the tidiest way to do this while preserving @GaryvanderMerwe's solution is to check the month: if the returned date's month is the previous, then take the following week, and the opposite for the last - e.g. let's say we want the first and last Mondays in May: `if last.month == 6: last = month[-2][0] if first.month == 4: first = month[1][0]` – puntofisso May 09 '18 at 15:03
3
Based on Gary's answer :
import calendar
month = calendar.monthcalendar(2010, 7)
mondays = [week[0] for week in month if week[0]>0]
print mondays[-1]
26
This works for getting the last Sunday of the month even if the last week of the month has no Sunday.

Community
- 1
- 1

manu190466
- 1,557
- 1
- 9
- 17
0
A tiny improvement on manu's answer !
import calendar
month = calendar.monthcalendar(2010, 7)
day_of_month = max(month[-1][calendar.SUNDAY], month[-2][calendar.SUNDAY])
print day_of_month

ticktock
- 627
- 7
- 12