tkyass
tkyass

Reputation: 3186

number of weeks in a given month python

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!

Upvotes: 3

Views: 7808

Answers (2)

Danielle M.
Danielle M.

Reputation: 3662

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

Upvotes: 11

steveman
steveman

Reputation: 139

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?

Upvotes: 2

Related Questions