I have already searched this question on stack overflow, but didn't find something that helped me or simply didn't understand them. What I want is a way to affirm that the user has entered the time in the following format hh:mm-hh:mm
. example:13:30-14:30
. I don't mind the format being 12hr or 24hr. Also the time needs to be restricted, in the sense that minutes should not go beyond 59 and hours should not go beyond 23. I've seen solutions that make use of regex, and I've seen the official documentation as well, but I find it hard to understand. So if anyone is using regex for an answer I don't mind accepting it as long as the answer explains the meaning of the regex expression.
pattern=r'[0-2][0-9]:[0-5][0-9]-[0-2][0-9]:[0-5][0-9]'
This was my attempt, but as it is clearly visible this has a lot of bugs. According to this expression,29:58-29:59
is a valid time, which of course isn't.
Regex will just make it more complicated. Use time.strptime() instead to parse if the time is correct. With the usage of the time
module, you can highly customize this to read 12h or 24h format, read the string "AM" or "PM", etc.
Then if you wish to also validate if the 2nd time is greater than the 1st time, you can easily use the functionalities in the time
module to perform this too.
import time
for data in [
"13:30-14:30",
"13:61-14:30",
"13:30-14:99",
"00:00-23:59",
"00:0023:59",
"XY:10-12:30",
"01:44-06:00",
"-11:10-12:30",
"11:10-12:30",
"26:10-34:12",
]:
print(data)
# Parse as 24h format
try:
start_time, _, end_time = data.partition("-")
start_time = time.strptime(start_time, "%H:%M")
end_time = time.strptime(end_time, "%H:%M")
except Exception as error:
print("\tThe time is invalid in 24h format!")
else:
print("\tThe time is valid in 24h format")
# Parse as 12h format
try:
start_time, _, end_time = data.partition("-")
start_time = time.strptime(start_time, "%I:%M")
end_time = time.strptime(end_time, "%I:%M")
except Exception as error:
print("\tThe time is invalid in 12h format!")
else:
print("\tThe time is valid in 12h format")
Output:
13:30-14:30
The time is valid in 24h format
The time is invalid in 12h format!
13:61-14:30
The time is invalid in 24h format!
The time is invalid in 12h format!
13:30-14:99
The time is invalid in 24h format!
The time is invalid in 12h format!
00:00-23:59
The time is valid in 24h format
The time is invalid in 12h format!
00:0023:59
The time is invalid in 24h format!
The time is invalid in 12h format!
XY:10-12:30
The time is invalid in 24h format!
The time is invalid in 12h format!
01:44-06:00
The time is valid in 24h format
The time is valid in 12h format
-11:10-12:30
The time is invalid in 24h format!
The time is invalid in 12h format!
11:10-12:30
The time is valid in 24h format
The time is valid in 12h format
26:10-34:12
The time is invalid in 24h format!
The time is invalid in 12h format!
For the possible formats, see: