正则表达式只会让它变得更复杂。如果时间正确,请改用time.strptime() 解析。使用time模块,您可以高度自定义它以读取12h或24h格式,读取字符串“AM”或“PM”等。
如果您还想验证第二次是否大于第一次,您也可以轻松使用time 模块中的功能来执行此操作。
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")
输出:
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!
有关可能的格式,请参阅: