【问题标题】:Find number of weeks in a month查找一个月中的周数
【发布时间】:2016-08-10 11:00:13
【问题描述】:

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

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

【问题讨论】:

  • 你如何定义一个月的周数?

标签: python week-number


【解决方案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

【讨论】:

    【解决方案2】:

    另一个数学解:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-18
      • 2010-12-20
      • 2011-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多