【问题标题】:number of weeks in a given month python给定月份python的周数
【发布时间】:2016-08-26 21:28:14
【问题描述】:

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

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

提前致谢!

【问题讨论】:

标签: python calendar


【解决方案1】:

这是一个快速的:

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

数行数:)

len(calendar.month(2016,10).split('\n')) - 3

编辑:约书亚克莱因在 cmets 中对这个答案的回答更加优雅:

len(calendar.monthcalendar(2015,9))

【讨论】:

  • 或者,calendar.month(2016,10).count('\n')-2
  • 更好len(calendar.monthcalendar(2015,9))
  • 感谢@JoshuaKlein 提供优雅的解决方案
【解决方案2】:

首先想到的是:获取该月第一天的周数和该月最后一天的周数。按月延长的周数就是周数的差。

获取日期的周数:How to get week number in Python?

【讨论】:

    猜你喜欢
    • 2012-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多