【发布时间】:2020-11-10 10:23:15
【问题描述】:
我需要使用 try-except 来验证日期和时间的输入字符串。输入格式应该是 MM/DD/YYYY HH:MM:SS。如果 validate 函数返回 false,则它无效。我尝试了无效输入,但 try-except 没有按预期工作。未打印错误消息。我的代码有什么问题?如何解决?谢谢。
def validate_user_input(input_string):
# check the input validation
validation = True
if input_string[2] != "/" or input_string[5] != "/":
validation = False
elif int(date) > 31 or int(date) < 1:
validation = False
elif int(month) > 12 or int(month) < 1:
validation = False
elif int(hour) < 0 or int(hour) > 24:
validation = False
elif int(minute) < 0 or int(minute) > 59:
validation = False
elif int(second) < 0 or int(second) > 59:
validation = False
return validation
input = input("Please input a date and time within the format of MM/DD/YYYY HH:MM:SS")
# get the information from the input
year = input[6:10]
month = input[0:2]
date = input[3:5]
hour = input[11:13]
minute = input[14:16]
second = input[17:19]
# try-except
try:
validate_user_input(input) == False
print("Your input is valid!")
except:
print("Error: the input date and time is invalid!")
【问题讨论】:
-
附带说明,您的代码将拒绝完全有效的日期和时间“12/31/2005 23:59:60”(leap second),以及其他时区的等价物。
-
为什么你认为应该在你的 try 块中抛出错误?
标签: python function boolean try-except