如何检查leap年日期是否有效

时间:2018-11-02 13:02:23

标签: python validation leap-year

我试图检查日期是否有效,但是我一直试图找出trying年日期是否有效。我继续收到以下消息:

最后一次运行于02/11/2018,12:49:03 您的函数说29/2/1754有效,但无效。

我知道这不是a年。我试图在有效日期函数中,每年不是is年的时候都返回False的值。

您能给我的任何信息,将不胜感激。谢谢

def isLeapYear(y):
    assert y > 1753, False
    return y % 4 == 0 and (y % 100 != 0 or y % 400 == 0)


def daysIn(y, m):
    assert 1 <= m <= 12, False
    if m == 9 or m == 4 or m == 6 or m == 11:
        return 30
    elif m == 1 or m == 'March' or m == 'May' or m == 'July':
        return 31
    elif m == 8 or m == 10 or m == 12 or m == 3 or m == 5 or m == 7:
        return 31
    elif m == 2 and isLeapYear(y) is True:
        return 29
    elif m == 2 and isLeapYear(y) is False:
        return 28
    else:
        return False


def validDate(y, m, d):

    try:
        if daysIn(y, m) and isLeapYear(y):
            return True
    except AssertionError:
        return False

    if y > 1753 and 1 <= m <= 12 and 1 <= d <= 31:
        return True
    elif y == isLeapYear(y) and m == 2 and d == 29:
        return False
    else:
        return False


if __name__ == "__main__":
    isLeapYear(2012)
    daysIn(2012, 10)
    validDate(1752, 10, 10)

2 个答案:

答案 0 :(得分:1)

您可以使用标准库的datetime模块。

from datetime import date

def validDate(y, m, d):
    try:
        date(y, m, d)
        return True
    except ValueError:
        return False

答案 1 :(得分:1)

问题出在validDate函数中,在此函数中,您不检查日期,而仅当月份有天时(每个月为True)。

def validDate(y, m, d):
    assert 1 <= d <= daysIn(y, m)

或者如果validDate应该返回布尔值,请尝试:

def validDate(y, m, d):
    if y <= 1754:
        return False
    if not (1 <= m <= 12):
        return False
    if m in (1, 3, 5, 7, 8, 10, 12):
        days = 31
    elif m == 2:
        leap = y % 4 == 0 and (y % 100 != 0 or y % 400 == 0)
        days = 29 if leap else 28
    else:
        days = 30
    return 1 <= d <= days