2

For my program

I have a series of command line arguments that I need to check if they are valid before proceeding with the rest of the program.

One of the argument comes in the format

HH:MM(AM/PM) or HH:MM(am/pm)

examples: 11:20pm is valid or 11:40PM is valid but 11:32 is invalid (It is an expression of a 12Hr digital clock with a AM/PM at the end.

This is the regex expression I have come up with

mo = re.search(r'[0-1][0-2]:[0-5][0-9][APap][Mm]', time)

however what I need to do is come up with a way of checking if the time variable matches the set pattern

1
  • Is there anything else between 0 and 1? Commented May 16, 2016 at 23:18

1 Answer 1

7

Attempt to match it with datetime.datetime.strptime() and handle the error if it fails (with whatever behavior you'd like).

for s in ('11:20pm', '11:40PM', '11:32'):
    try:
        print(datetime.datetime.strptime(s, '%H:%M%p'))
    except ValueError:
        print('No.')

Result:

1900-01-01 11:20:00
1900-01-01 11:40:00
No.
Sign up to request clarification or add additional context in comments.

Comments

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.