-4

Can someone suggest a function to return number of weeks in a month? for example:

def num_of_weeks(year, month):
    # Do calulation
    return int(num)

# In 2016 Julay we had five weeks
print num_of_weeks(2016, 1)
>> 5

print num_of_weeks(2016, 5)
>> 6
chridam
  • 100,957
  • 23
  • 236
  • 235
Ehsan Toghian
  • 548
  • 1
  • 6
  • 26

2 Answers2

1

You can do it using calendar built-in module. My example looks hackish, but still it handles your task:

def num_of_weeks_in_month(year, month):
    import calendar
    return calendar.month(year, month).count('\n') - 2

print num_of_weeks_in_month(2016, 8)  # print 5
print num_of_weeks_in_month(2016, 9)  # print 5
print num_of_weeks_in_month(2016, 10)  # print 6
vadimhmyrov
  • 169
  • 7
1

Another mathematical solution:

def num_of_weeks_in_month(year, month):
    from math import ceil
    from calendar import monthrange

    return int(ceil(float(monthrange(year, month)[0]+monthrange(year,month)[1])/7))
Ehsan Toghian
  • 548
  • 1
  • 6
  • 26