【问题标题】:number of leap days in python with month and day带有月份和日期的python中的闰日数
【发布时间】:2020-11-04 13:23:58
【问题描述】:

如果开始日期晚于闰年,如何计算闰日数并使其忽略闰年 2 月 29 日或结束日期在 2 月 29 日之前。

这是我的进度,如有混乱,请见谅。我是新人。

def compute_leap_years(start_year, start_month, start_day, end_year, end_month, end_day):
    if calendar.isleap(start_year) and (start_month >= 3 and not(bool(start_month == 2 and start_day == 29))):
        start_year = start_year + 1
    if calendar.isleap(end_year) and (end_month <= 2 and not(bool(end_month == 2 and end_day == 29))):
        end_year = end_year - 1
    days = calendar.leapdays(start_year, end_year)
    return days

【问题讨论】:

    标签: python python-3.x datetime calendar


    【解决方案1】:

    我不熟悉calendar.leapdays(),但它似乎不包括最后一年。

    如果是这种情况并假设您的输入都是ints,这应该可行。

    import calendar
    
    def compute_leap_years(start_year, start_month, start_day, end_year, end_month, end_day):
        # initialize your leapdays so you can keep a running count
        days = calendar.leapdays(start_year, end_year)
        # set yourself an end date as an int for easy comparison
        # here, end_day is zero padded to 2 characters to characterize
        # the dates as an increasing number from 101 to 1231
        end_date = int(f'{end_month}{end_day:02}')
        if calendar.isleap(start_year) and start_month >= 3:
            # if the start month is after february we know we have to subtract a day
            days -= 1
        if calendar.isleap(end_year) and end_date > 228:
            # and add a day if the excluded year is past the 28th and a leap year
            days += 1
        return days
    
    # test cases
    print(compute_leap_years(2016, 3, 2, 2020, 2, 28)) # 0
    print(compute_leap_years(2016, 1, 2, 2020, 2, 28)) # 1
    print(compute_leap_years(2016, 1, 2, 2020, 2, 29)) # 2
    print(compute_leap_years(2020, 1, 2, 2020, 2, 28)) # 0
    print(compute_leap_years(2020, 1, 2, 2020, 2, 29)) # 1
    

    请记住,这不会检查无效的日期输入。

    顺便说一句,几乎没有理由将比较转换为bool,因为 python 具有“真实”值。

    【讨论】:

      猜你喜欢
      • 2021-08-21
      • 2021-12-09
      • 2023-03-16
      • 1970-01-01
      • 2023-04-11
      • 2013-03-08
      • 2014-12-04
      • 2015-07-10
      • 1970-01-01
      相关资源
      最近更新 更多