【问题标题】:Python - count frequency of specific day within a monthPython - 计算一个月内特定日期的频率
【发布时间】:2016-11-10 02:51:14
【问题描述】:

我正在尝试计算给定月份内特定日期的频率。例如,本月(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

我的目标是计算给定月份内特定日期的频率。任何建议将不胜感激。非常感谢。

问候,

阿诺德 A.

【问题讨论】:

    标签: python python-3.x calendar


    【解决方案1】:

    range(start, stop) 不包括停止位,因为monthrange(year, month) 返回(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})
    

    【讨论】:

      【解决方案2】:

      你有一个错误,范围从 start 到 end-1,你可以这样做:

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

      【讨论】:

        猜你喜欢
        • 2017-01-16
        • 1970-01-01
        • 1970-01-01
        • 2014-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多