我如何获得某个月的最后一个星期一(或其他日子)?
答案 0 :(得分:8)
查看dateutil:
from datetime import datetime
from dateutil import relativedelta
datetime(2010,7,1) + relativedelta.relativedelta(day=31, weekday=relativedelta.MO(-1))
返回
datetime.datetime(2010, 7, 26, 0, 0)
答案 1 :(得分:8)
使用stdlib中的calendar模块:
import calendar
cal = calendar.Calendar(0)
month = cal.monthdatescalendar(2010, 7)
lastweek = month[-1]
monday = lastweek[0]
print(monday)
2010-07-26
答案 2 :(得分:1)
import calendar
month = calendar.monthcalendar(2010, 7)
mondays = [week[0] for week in month if week[0]>0]
print mondays[-1]
26
这适用于获取本月的最后一个星期日,即使该月的最后一周没有星期天。
答案 3 :(得分:0)
对manu的回答微不足道的改进!
import calendar
month = calendar.monthcalendar(2010, 7)
day_of_month = max(month[-1][calendar.SUNDAY], month[-2][calendar.SUNDAY])
print day_of_month