有人可以建议一个函数返回一个月内的周数吗? 例如:
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
答案 0 :(得分:1)
您可以使用日历内置模块执行此操作。我的例子看起来很乱,但它仍处理你的任务:
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
答案 1 :(得分:1)
另一种数学解决方案:
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))