How do I get the last Monday (or another day) of a given month?
Using the calendar module from stdlib:
import calendar cal = calendar.Calendar(0) month = cal.monthdatescalendar(2010, 7) lastweek = month[-1] monday = lastweek[0] print(monday) 2010-07-26
Check out dateutil :
from datetime import datetime from dateutil import relativedelta datetime(2010,7,1) + relativedelta.relativedelta(day=31, weekday=relativedelta.MO(-1))
returns
datetime.datetime(2010, 7, 26, 0, 0)
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 to get the last Sunday of the month, even if there is no Sunday in the last week of the month.
A slight improvement in the answer to manu!
import calendar month = calendar.monthcalendar(2010, 7) day_of_month = max(month[-1][calendar.SUNDAY], month[-2][calendar.SUNDAY]) print day_of_month
Source: https://habr.com/ru/post/1438605/More articles:haproxy with SSL and Notls - sslHow to break a line on a web page? - sql-serverRefresh graphics for timer points - javaiOS PDF for easy text parsing - iosPG :: Server error unexpectedly closed the connection - ruby | fooobar.comRunning a cycle in Javascript - performanceIs JavaScript optimization for loops really necessary? - performanceHow to randomly generate objectid in node js - node.jsCSS Responsive Grid 1px Problem - cssLog in to YouTube using WebRequests in C # - c #All Articles