2012-10-19 50 views

回答

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 
2

我會做這樣的:

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 
0

爲此,您可以使用ISO週數:一週的某一天(1

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) 

一般=週一,7 =星期日)的計算公式是:

num_days = ((e_week - b_week) + 
      (-1 if b_weekday > day else 0) + 
      (1 if e_weekday >= day else 0)) 
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()

1

又如使用calendardatetime

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)) 
+1

如果你留下一些反饋,我很想改進這個:)。 – mgilson

+0

我認爲在某些情況下這可能是錯的。如果本月的第一天和第二天是星期六和星期日,該怎麼辦?然後29日和30日也是週六和週日。 –

+0

@AlexanderStefanov - 那麼?我在這裏看不到你的觀點...(這可能是錯誤的已經足夠清楚了,但我不明白你的理性) – mgilson

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已經指出的那樣,你可以不設名單-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] 
+0

爲什麼迭代兩次?'如果週日(y,m,d + 1)== SUNDAY =='print sum(1範圍內的d(* monthrange(y,m))' – mgilson

+0

@mgilson保持簡單 - 我實際上有'sum(1 ...)'在解釋器中打開,但將其更改回列表comp和.count以便張貼在這裏:) –

2

我正好需要一個解決方案,但並不理想與解決方案在這裏,所以我想到了我自己:

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) 
相關問題