4

如何获得给定月份的最后一个星期一(或其他日期)?

4

4 回答 4

9

看看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)
于 2012-10-09T09:06:54.497 回答
7

使用标准库中的日历模块:

import calendar
cal = calendar.Calendar(0)
month = cal.monthdatescalendar(2010, 7)
lastweek = month[-1]
monday = lastweek[0]
print(monday)

2010-07-26
于 2012-10-09T09:10:47.100 回答
1

根据加里的回答

import calendar
month = calendar.monthcalendar(2010, 7)
mondays = [week[0] for week in month if week[0]>0]
print mondays[-1]

26

即使该月的最后一周没有星期日,这也适用于获取该月的最后一个星期日。

于 2015-02-26T18:14:55.677 回答
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 
于 2015-03-30T05:11:56.543 回答