Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python—一个月内特定日期的计数频率_Python_Python 3.x_Calendar - Fatal编程技术网

Python—一个月内特定日期的计数频率

Python—一个月内特定日期的计数频率,python,python-3.x,calendar,Python,Python 3.x,Calendar,我试图计算一个月内特定日期的频率。例如,本月(2016年11月),有4个星期一、5个星期二、5个星期三、4个星期四、4个星期五、4个星期六和4个星期日 到目前为止,我已经做到了 import calendar from calendar import weekday, monthrange, SUNDAY import datetime now = datetime.datetime.now() year, month = now.year, now.month days = [weekd

我试图计算一个月内特定日期的频率。例如,本月(2016年11月),有4个星期一、5个星期二、5个星期三、4个星期四、4个星期五、4个星期六和4个星期日

到目前为止,我已经做到了

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))]
然而,当我试图打印多少,例如,本月内的星期二,它给了我不正确的结果

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
如果我检查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
我的目标是计算给定月份内特定日期的频率。任何建议都将不胜感激。非常感谢

问候,


Arnold A.

您有一个“关一”错误,范围从开始到结束-1,您可以这样做:

[weekday(year, month, d) for d in range(1, monthrange(year, month)[1]+1)]

如果出现“关闭一次”错误,范围从开始到结束-1,则可以执行以下操作:

[weekday(year, month, d) for d in range(1, monthrange(year, month)[1]+1)]
范围(开始、停止)
不包括停止,因为
monthrange(年、月)
返回
(1,30)
范围将停止在
29
。所以稍微更新一下:

>>> 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})
范围(开始、停止)
不包括停止,因为
monthrange(年、月)
返回
(1,30)
范围将停止在
29
。所以稍微更新一下:

>>> 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})