arnold - 7 months ago 54
Python Question

# Python - count frequency of specific day within a month

I am trying to count the frequency of specific day within a given month. For example, this month (November 2016), there are 4 Mondays, 5 Tuesdays, 5 Wednesdays, 4 Thursdays, 4 Fridays, 4 Saturdays, and 4 Sundays.

So far here is what I have already done.

``````import calendar
from calendar import weekday, monthrange, SUNDAY
import datetime

now = datetime.datetime.now()

year, month = now.year, now.month

days = [weekday(year, month, d) for d in range(*monthrange(year, month))]
``````

However, when I tried to print how many, for example,Tuesdays within this month, it gave me incorrect result.

``````In  [1]: print(days.count(calendar.WEDNESDAY))
Out [1]: 4 # should be 5 instead of 4
In  [2]: print(days.count(calendar.TUESDAY))
Out [2]: 5 # this one is correct
``````

If I checked the calendar within Python itself, it showed me the right calendar.

``````In  [4]: calendar.prmonth(year, month)

November 2016
Mo Tu We Th Fr Sa Su
1  2  3  4  5  6
7  8  9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
``````

My objective is to count the frequency of specific day within the given month. Any suggestion will be much appreciated. Thanks a lot.

Regards,

Arnold A.

`range(start, stop)` is exclusive of the stop, as `monthrange(year, month)` returns `(1, 30)` the range will stop at `29`. So a slight update:
``````>>> s, e = monthrange(year, month)