如何在Python中获取当月的星期日数?
有人对此有任何想法吗?
答案 0 :(得分:6)
这会根据您的需要为您提供当月的星期日数:
import calendar
from datetime import datetime
In [367]: len([1 for i in calendar.monthcalendar(datetime.now().year,
datetime.now().month) if i[6] != 0])
Out[367]: 4
答案 1 :(得分:4)
我的看法:(节省了担心在正确的月份等...)
from calendar import weekday, monthrange, SUNDAY
y, m = 2012, 10
days = [weekday(y, m, d+1) for d in range(*monthrange(y, m))]
print days.count(SUNDAY)
或者,正如@mgilson指出的那样,你可以取消list-comp,并将其全部包装为生成器:
sum(1 for d in range(*monthrange(y,m)) if weekday(y,m,d+1)==SUNDAY)
我想,你可以投入:
from collections import Counter
days = Counter(weekday(y, m, d + 1) for d in range(*monthrange(y, m)))
print days[SUNDAY]
答案 2 :(得分:3)
我会这样做:
import datetime
today = datetime.date.today()
day = datetime.date(today.year, today.month, 1)
single_day = datetime.timedelta(days=1)
sundays = 0
while day.month == today.month:
if day.weekday() == 6:
sundays += 1
day += single_day
print 'Sundays:', sundays
答案 3 :(得分:3)
我碰巧需要一个解决方案,但是这里的解决方案并不令人满意,所以我想出了自己的解决方案:
import calendar
year = 2016
month = 3
day_to_count = calendar.SUNDAY
matrix = calendar.monthcalendar(year,month)
num_days = sum(1 for x in matrix if x[day_to_count] != 0)
答案 4 :(得分:1)
使用calendar
和datetime
的另一个例子:
import datetime
import calendar
today = datetime.date.today()
m = today.month
y = today.year
sum(1 for week in calendar.monthcalendar(y,m) if week[-1])
或许稍微快一点的方法是:
first_day,month_len = monthrange(y,m)
date_of_first_sun = 1+6-first_day
print sum(1 for x in range(date_of_first_sun,month_len+1,7))
答案 5 :(得分:0)
您可以使用ISO周号来完成此操作:
from datetime import date
bom = date.today().replace(day=1) # first day of current month
eom = (date(bom.year, 12, 31) if bom.month == 12 else
(bom.replace(month=bom.month + 1) - 1)) # last day of current month
_, b_week, _ = bom.isocalendar()
_, e_week, e_weekday = eom.isocalendar()
num_sundays = (e_week - b_week) + (1 if e_weekday == 7 else 0)
通常对于一周中的特定日期(1 =星期一,7 =星期日),计算结果为:
num_days = ((e_week - b_week) +
(-1 if b_weekday > day else 0) +
( 1 if e_weekday >= day else 0))
答案 6 :(得分:0)
import calendar
MONTH = 10
sundays = 0
cal = calendar.Calendar()
for day in cal.itermonthdates(2012, MONTH):
if day.weekday() == 6 and day.month == MONTH:
sundays += 1
注意: 以下是Calendar.itermonthdates的文档:
返回迭代器一个月。迭代器将产生datetime.date 价值观并将一直持续整整几周,因此它会产生 在指定月份之外的日期。
这就是为什么需要day.month == MONTH
如果您希望工作日在0-6范围内,请使用day.weekday()
,
如果您希望它们在1-7范围内,请使用day.isoweekday()