Python: get last Monday of July 2010

妖精的绣舞 提交于 2021-01-23 05:02:07

问题


How do I get the last Monday (or other day) of a given month?


回答1:


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



回答2:


Have a look at 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)



回答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.




回答4:


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 


来源:https://stackoverflow.com/questions/12796389/python-get-last-monday-of-july-2010

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!