在python中验证日期mm / dd / yyyy表单

时间:2016-11-15 14:22:12

标签: python-3.5

我有两个问题1_我无法使用此表单05/04/2011继续给我一个错误 2_我无法阻止用户使用负数。 这是代码:

def main():
    # ask the user for a date as a string in the form mm/dd/yyyy
    date = input("Please enter a date in form mm/dd/yyyy: ")
    months, days, years = date.split("/")

    # ask about the month 
    m = range(1,13)
    months = m[eval(months)-1]
    # april have only 30 days
    if months in range(4,5):
        D = range(1,31)
        Days = D[eval(days)-1]
    # june have only 30 days
    elif months in range(6,7):
        D = range(1,31)
        Days = D[eval(days)-1]
    # september have only 30 days
    elif months in range(9,10):
        D = range(1,31)
        Days = D[eval(days)-1]
    # november have only 30 days 
    elif months in range(11,12):
        D = range(1,31)
        Days = D[eval(days)-1]
    # ask about days 
    d = range(1,32)
    days = d[eval(days)-1]
    # ask about the years
    y = range(1,2017)
    years = y[eval(years)-1]
    if months <= 0:
        print("you can't use a nagatve number")
    if days <= 0:
        print("you can't use negaive numbers")
    if years <= 0:
        print("you can't use negaiive numbers")
    print(months,"/",days,"/",years,"is a valid date")
main()

1 个答案:

答案 0 :(得分:0)

您应该查看Python datetime库,特别是datetime.strptime(date_string, format)

您可以使用:

,而不是编写自己的错误日期解析器
datestring = input("Please enter a date in form mm/dd/yyyy: ")
try:
    date = datetime.strptime(datestring, '%m/%d/%Y')
except ValueError:
    print("Invalid date entered!")

您的代码包含一些非常糟糕的做法,例如,您不应该使用eval来简单地将字符串计算为整数,而在整个地方使用它。而不是:

m = range(1,13)
months = m[eval(months)-1]

你可以简单地写一下:

months = int(months)

months in range(4,5)等代码可以重写为months == 4,但您也可以使用if months in [4, 6, 9, 1]:。但你完全忘记了二月,这也取决于当年是否是闰年。