[英]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.
例如,本月(2016年11月)有4个星期一,5个星期二,5个星期三,4个星期四,4个星期五,4个星期六和4个星期日。
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. 如果我在Python本身中检查了日历,它将显示正确的日历。
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. 阿诺德A.
您遇到一个错误,范围从开始到结束-1,您可以改为执行以下操作:
[weekday(year, month, d) for d in range(1, monthrange(year, month)[1]+1)]
range(start, stop)
is exclusive of the stop, as monthrange(year, month)
returns (1, 30)
the range will stop at 29
. range(start, stop)
不包括stop,因为monthrange(year, month)
返回(1, 30)
monthrange(year, month)
(1, 30)
,范围将在29
停止。 So a slight update: 所以稍作更新:
>>> s, e = monthrange(year, month)
>>> days = [weekday(year, month, d) for d in range(s, e+1)]
>>> collections.Counter(days)
Counter({0: 4, 1: 5, 2: 5, 3: 4, 4: 4, 5: 4, 6: 4})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.