python 月份和日期的闰日数

number of leap days in python with month and day

如果开始日期晚于闰年,如何计算闰日并忽略闰年 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

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

如果是这种情况,假设您的输入全部是 int,这应该可行。

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 具有“真实”值。