简体   繁体   English

python中带有月和日的闰日数

[英]number of leap days in python with month and day

How to compute the number of leap days and make it ignore the leap year if the start date is after Feb 29 or the end date is before Feb 29.如果开始日期在 2 月 29 日之后或结束日期在 2 月 29 日之前,如何计算闰日数并使其忽略闰年。

Here is my progress, sorry if it's messy.这是我的进展,抱歉,如果它很乱。 I'm new.我是新来的。

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

I'm not familiar with calendar.leapdays() but it looks like it excludes the final year.我不熟悉calendar.leapdays()但它看起来不包括最后一年。

If that's the case and assuming your input is all int s, this should work.如果是这种情况并且假设您的输入都是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

Keep in mind this does no checks for invalid date entry.请记住,这不会检查无效的日期输入。

As an aside, there is almost never a reason to convert a comparison to bool as python has "truthy" values.顺便说一句,几乎没有理由将比较转换为bool因为 python 具有“真实”值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM