3

I need to use try-except to validate the input string of a date and time.The input format should be MM/DD/YYYY HH:MM:SS. If the validate function returns false, then it's not valid.I tried a invalid input, but the try-except didn't work as expected. The error message wasn't printed. What's wrong with my code? How to fix it? Thanks.

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!")
2
  • 1
    As a side-note, your code will reject the entirely valid date and time "12/31/2005 23:59:60" (leap second), and equivalents in other time-zones. Commented Jul 21, 2020 at 5:23
  • Why do you believe an error should have been thrown inside your try block? Commented Jul 21, 2020 at 6:11

3 Answers 3

3

The except will only catch an exception if one is thrown and not caught by an earlier try-except. You are not raiseing anything in your code, so the except block will never run. You should instead throw an error, perhaps a ValueError, when the validate_user_input function returns False:

try:
    if not validate_user_input(input):
        raise ValueError("Bad input")
except:
    ...
Sign up to request clarification or add additional context in comments.

1 Comment

Amazing! It works expectedly. Thank you so much. I just learned this try-except stuff. Your answer really helps a lot.
2

Use an if statement instead. This should be simpler than using try and except.

if validate_user_input(input) == False:
    print("Your input is valid!")
else:
    print("Error: the input date and time is invalid!")

3 Comments

The alternative would be to change the validate_user_input function to raise an exception for invalid input and return nothing otherwise. That would also let you explain how the input is invalid, whether it's punctuation or invalid month number.
Error messages are help messages; they should assist the user in achieving their tasks.
If-else works as well, but try-except is required from my assignment. Thank you though.
1
# try-except
try: 
    validate_user_input(input) == False
    print("Your input is valid!")
except:
    print("Error: the input date and time is invalid!")

Seems like you're going to validate the entered date & time from the input. But this code lines doesn't do anything. It check the condition without doing anything, @dogman288 answer make it happen. I would like to suggest a library call python-dateutil. Within few lines you can do your validations very easily, I hope this will save your time. Just comment the relevant outputs.

from dateutil.parser import parse
from dateutil.parser._parser import ParserError


def validate_user_input(input_string: str):
    try:
        parse(input_string)
        print("Your input is valid!")
    except ParserError as error:
        print(error)


validate_user_input("12/31/2005 23:59:6")  # Your input is valid!
validate_user_input("13/31/2005 23:59:6")  # month must be in 1..12: 13/31/2005 23:59:6
validate_user_input("12/32/2005 23:59:6")  # day is out of range for month: 12/32/2005 23:59:6
validate_user_input("12/31/200511111 23:59:6")  # year 200511111 is out of range: 12/31/200511111 23:59:6
validate_user_input("12/31/2005 24:59:6")  # hour must be in 0..23: 12/31/2005 24:59:6
validate_user_input("12/31/2005 23:61:6")  # minute must be in 0..59: 12/31/2005 23:61:6
validate_user_input("12/31/2005 23:59:61")  # second must be in 0..59: 12/31/2005 23:59:61
validate_user_input("")  # String does not contain a date: 
validate_user_input("some_string")  # Unknown string format: some_string

2 Comments

Thank you so much. Your answer is helpful. Good to learn the new knowledge.
You're welcome @Timon, comment here if you need any help from me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.