3

I'm trying to get the number of weeks in any month. for example:

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

Is there any elegant way to find out this number? tried using calendar and datetime but I couldn't find anything that can help me solve my problem.

P.S I'm using python 2.6

Thanks in advance!

tkyass
  • 2,968
  • 8
  • 38
  • 57
  • Possible duplicate of [Python: Number of the Week in a Month](http://stackoverflow.com/questions/7029261/python-number-of-the-week-in-a-month). Take this answer, apply it to the last day of the month, and there's your solution. – Prune Aug 26 '16 at 21:49

2 Answers2

11

Here's a quicky:

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

Count the lines :)

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

edit: joshua klein's answer in the comments to this answer is way more elegant:

len(calendar.monthcalendar(2015,9))
Danielle M.
  • 3,607
  • 1
  • 14
  • 31
2

First thing that comes to mind: get the week number for the first day of the month, and the week number of the last day of the month. The number of weeks strechted by the month is then the difference of the week numbers.

To get the week number for a date: How to get week number in Python?

Community
  • 1
  • 1
steveman
  • 139
  • 7