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

我试图检查日期是否有效,但我一直试图找出闰年日期是否有效。我不断收到这条消息,上面写着:


LAST RUN on 02/11/2018, 12:49:03 你的函数说 29/2/1754 是有效的,但它是无效的。


我知道这不是闰年。每当一年不是闰年时,我都试图在 validDate 函数中返回一个 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)


GCT1015
浏览 219回答 2
2回答

Qyouu

您可以使用标准库 datetime 模块。from datetime import datedef validDate(y, m, d):&nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; date(y, m, d)&nbsp; &nbsp; &nbsp; &nbsp; return True&nbsp; &nbsp; except ValueError:&nbsp; &nbsp; &nbsp; &nbsp; return False

潇潇雨雨

问题出在validDate函数中,您不检查日期,而仅检查月份是否有天数(每个月都为 True)。def validDate(y, m, d):&nbsp; &nbsp; assert 1 <= d <= daysIn(y, m)或者如果validDate应该返回一个布尔值,请尝试:def validDate(y, m, d):&nbsp; &nbsp; if y <= 1754:&nbsp; &nbsp; &nbsp; &nbsp; return False&nbsp; &nbsp; if not (1 <= m <= 12):&nbsp; &nbsp; &nbsp; &nbsp; return False&nbsp; &nbsp; if m in (1, 3, 5, 7, 8, 10, 12):&nbsp; &nbsp; &nbsp; &nbsp; days = 31&nbsp; &nbsp; elif m == 2:&nbsp; &nbsp; &nbsp; &nbsp; leap = y % 4 == 0 and (y % 100 != 0 or y % 400 == 0)&nbsp; &nbsp; &nbsp; &nbsp; days = 29 if leap else 28&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; days = 30&nbsp; &nbsp; return 1 <= d <= days
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python