给定月份python中的周数

tky*_*ass 0 python calendar

我正在尝试获取任何月份的周数。例如:

for this month August 2016, the days of the month streches over 5 weeks. while for October 2016 the number of weeks are 6

有什么优雅的方法可以找到这个数字吗?尝试使用日历和日期时间,但找不到任何可以帮助我解决问题的方法。

PS我正在使用python 2.6

提前致谢!

Dan*_* M. 6

这是一个快捷方式:

>>> import calendar
>>> print calendar.month(2016,10)
    October 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
31
Run Code Online (Sandbox Code Playgroud)

计算行数:)

len(calendar.month(2016,10).split('\n')) - 3
Run Code Online (Sandbox Code Playgroud)

编辑:约书亚·克莱因(Joshua klein)在这个答案的评论中的答案更为优雅:

len(calendar.monthcalendar(2015,9))
Run Code Online (Sandbox Code Playgroud)

  • 更好的len(calendar.monthcalendar(2015,9))` (4认同)
  • 或者,`calendar.month(2016,10).count('\ n')-2` (3认同)