Firehawk
Firehawk

Reputation: 5

How to check string is laid out in correct format (Python)

I am coding a program which needs to import log files. The user must input the name of the file in the correct order of 'DD-HH.MM' (day, hour, minute). Is there any way to validate that the users input is in the correct order?

Thanks in advance

Upvotes: 0

Views: 3852

Answers (2)

Jan Buchar
Jan Buchar

Reputation: 1322

You could either use regular expressions, or try to parse the date with time.strptime and see if there are any exceptions. See https://docs.python.org/2/library/time.html#time.strptime

The strptime way could be something like this:

try:
    time.strptime(input_string, "%d-%H.%M")
except ValueError:
    print("Incorrect date format")

Be sure to check the docs and see if the placeholders (%d, %H, ...) really represent the ranges and formats you want to check

Upvotes: 3

user3745735
user3745735

Reputation:

You can try using this regular expression: \d\d-\d\d\.\d\d (I'm not great at writing regular expressions, correct me if I'm wrong). You might also want to check that the date / hour / minute values are valid (i.e. within range).

import re
input = '12-12.12'
if re.match('\d\d-\d\d\.\d\d', input):
    print("it matches!")
else:
    print("it doesn't match!")

EDIT: the answer above is probably better.

EDIT EDIT: [0123]\d-\d\d\.[0-5]\d would be a slightly better regexp, it validates the month and minute but not the hour.

Upvotes: 0

Related Questions