找出一个月中的星期数

2024-04-26 01:04:34 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能建议一个函数来返回一个月内的周数吗? 例如:

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

Tags: of函数inreturndefyeardonum
2条回答

您可以使用日历内置模块来完成。我的示例看起来很粗糙,但它仍然可以处理您的任务:

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

另一个数学解:

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

相关问题 更多 >