简体   繁体   English

为什么我的脚本不接受有效日期作为用户输入?

[英]Why doesn't my script accept a valid date as user input?

The script works fine if I give it a date of 01/12/2021 .如果我给它一个日期01/12/2021 ,该脚本就可以正常工作。 But if I give it another date like today's as 01/18/2021 or any other the script says that the date isn't valid and prompts the user to enter the date in again.但是,如果我给它另一个日期,例如今天的01/18/2021或任何其他日期,脚本会说该日期无效并提示用户再次输入日期。

def print_reports(interactive,aws_account,aws_account_number):
    inputDate = input("Enter the date in format 'dd/mm/yyyy': ")
    day,month,year = inputDate.split('/')
    isValidDate = True
    try:
        datetime(int(year),int(month),int(day))
    except ValueError :
        isValidDate = False
        print("Date is not valid.")
        print_reports(interactive,aws_account,aws_account_number)

    if(isValidDate) :
        print(f"Input date is valid: {inputDate}")
        format= "%m%d%Y"
        inputDate = datetime.strptime(inputDate,"%m/%d/%Y")
        inputDate = inputDate.strftime(format)
    else:
        print(f"Input date is not valid: {inputDate}")
        print_reports(interactive,aws_account,aws_account_number)
    myclient = connect_db()
    mydb = myclient["aws_inventories"]
    instance_col = "ec2_list_" + inputDate
    instance_col = mydb[instance_col]
    print_reports(interactive,aws_account,aws_account_number)

This is the output I get if I put in some different dates:如果我输入一些不同的日期,这是我得到的 output:

Enter the date in format 'dd/mm/yyyy': 01/12/2021
Input date is valid: 01/12/2021
Enter the date in format 'dd/mm/yyyy': 01/13/2021
Date is not valid.
Enter the date in format 'dd/mm/yyyy': 01/14/2021
Date is not valid.
Enter the date in format 'dd/mm/yyyy': 01/15/2021
Date is not valid.
Enter the date in format 'dd/mm/yyyy': 01/16/2021
Date is not valid.

Why won't my script accept any date other than 01/12/2021 as valid input?为什么我的脚本不接受01/12/2021年 1 月 12 日以外的任何日期作为有效输入?

01/16/2021 is not a valid date, since the year has only 12 months and not 16;). 01/16/2021年 1 月 16 日不是有效日期,因为一年只有 12 个月,而不是 16 个月;)。
Your code should be like this:你的代码应该是这样的:

def print_reports(interactive, aws_account, aws_account_number):
    inputDate = input("Enter the date in format 'dd/mm/yyyy': ")
    day, month, year = inputDate.split('/')
    try:
        datetime(int(day), int(month), int(year))
    except ValueError as e:
        print("Date is not valid.")
        return False

    print(f"Input date is valid: {inputDate}")
    inputDate = datetime.strptime(inputDate,"%d/%m/%Y")
    return True
myclient = connect_db()
mydb = myclient["aws_inventories"]
instance_col = mydb["ec2_list_" + inputDate]
while not success:
    global success
    success = print_reports(interactive, aws_account, aws_account_number)

You are asking for the format dd/mm/yyyy .您要求格式dd/mm/yyyy Yet, you are inputting (in what I assume) is a mm/dd/yyyy format.但是,您输入的(我假设)是mm/dd/yyyy格式。 If you try to parse 01/18/2021 in the format dd/mm/yyyy , then you would get the result that it is the first day in the 18th month in the year 2021 (which, of course, is impossible - there are only 12 months in the year).如果您尝试以dd/mm/yyyy格式解析01/18/2021 ,那么您会得到它是 2021 年第 18 个月的第一天的结果(当然,这是不可能的 - 有一年只有 12 个月)。 To fix this, you are going to either have to change your format to mm/dd/yyyy or input as 18/01/2021 .要解决此问题,您必须将格式更改为mm/dd/yyyy或输入为18/01/2021

To change the input checker to mm/dd/yyyy :要将输入检查器更改为mm/dd/yyyy

def print_reports(interactive, aws_account, aws_account_number):
    inputDate = input("Enter the date in format 'mm/dd/yyyy': ")
    month, day, year = inputDate.split('/') # changed order of month and day
    isValidDate = True
    try:
        datetime(int(year), int(month), int(day))
    except ValueError:
        isValidDate = False
        print("Date is not valid.")
        print_reports(interactive, aws_account, aws_account_number)

    if isValidDate:
        print(f"Input date is valid: {inputDate}")
        format = "%m%d%Y"
        inputDate = datetime.strptime(inputDate,"%m/%d/%Y")
        inputDate = inputDate.strftime(format)
    else:
        print(f"Input date is not valid: {inputDate}")
        print_reports(interactive,aws_account,aws_account_number)
    myclient = connect_db()
    mydb = myclient["aws_inventories"]
    instance_col = "ec2_list_" + inputDate
    instance_col = mydb[instance_col]
    print_reports(interactive,aws_account,aws_account_number)

Note that it looks like you are using the function datetime with the dd/mm/yyyy format, but you are using the mm/dd/yyyy format with datetime.strptime in the original code.请注意,您似乎使用的是dd/mm/yyyy格式的 function datetime时间,但您在原始代码中使用的是带有datetime.strptimemm/dd/yyyy格式。 In this code, it only uses the mm/dd/yyyy format, but you can always edit this easily to dd/mm/yyyy .在此代码中,它仅使用mm/dd/yyyy格式,但您始终可以轻松地将其编辑为dd/mm/yyyy

Edit: Looks like you are using recursion.编辑:看起来你正在使用递归。 Of course, instead, you should be using a while loop, as recursion is not needed here.当然,您应该使用while循环,因为这里不需要递归。 Also, you are using the isValidDate variable, but that is never actually used or needed:此外,您正在使用isValidDate变量,但实际上从未使用或需要它:

def print_reports(interactive, aws_account, aws_account_number):
    while True:
        inputDate = input("Enter the date in format 'mm/dd/yyyy': ")
        month, day, year = inputDate.split('/') # changed order of month and day
        try:
            datetime(int(year), int(month), int(day))
        except ValueError:
            print("Date is not valid.")
            continue

        print(f"Input date is valid: {inputDate}")
        format = "%m%d%Y"
        inputDate = datetime.strptime(inputDate,"%m/%d/%Y")
        inputDate = inputDate.strftime(format)

        myclient = connect_db()
        mydb = myclient["aws_inventories"]
        instance_col = "ec2_list_" + inputDate
        instance_col = mydb[instance_col]

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

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