我想比较用户输入的时间,以确保其在python中的格式正确
我正在编写一个程序,接受用户以am/pm格式输入的时间。我想确定,如果用户输入其他内容,它将导致错误,而不仅仅是程序崩溃。 我的意思是,用户必须以HH:MM am/pm格式输入时间。e、 g“下午2:00”或“上午11:00”以及任何其他要求出错的内容 我所能做的就是我想比较用户输入的时间,以确保其在python中的格式正确,python,python-3.x,Python,Python 3.x,我正在编写一个程序,接受用户以am/pm格式输入的时间。我想确定,如果用户输入其他内容,它将导致错误,而不仅仅是程序崩溃。 我的意思是,用户必须以HH:MM am/pm格式输入时间。e、 g“下午2:00”或“上午11:00”以及任何其他要求出错的内容 我所能做的就是 print("Make all inputs using the format 'hh:mm am/pm' e.g 10:00 am ... and add 0 before single numbers e.g 3 ==>
print("Make all inputs using the format 'hh:mm am/pm' e.g 10:00 am ... and add 0 before single numbers e.g 3 ==> 03" )
while True:
start = input("At what is the start time?: ")
end = input("At what is the end time?: ")
if len(start) != 8:
print("error! wrong value/format entered as the start time")
elif len(end) != 8:
print("error! wrong value/format entered as the end time")
else:
break
这里有两种方法,我个人更喜欢日期转换方法 日期转换法 我会检查是否可以将它们转换为日期Python对象。我使用了
%H:%M%p
,时间为小时:分钟am/pm(根据提示指定)
正则表达式方法
我将使用以下正则表达式:
r"^(?:1?[012]|[0-9]):[0-5][0-9]\s*(?:am|pm)$"i
这是一个Regex101:
非常感谢您!!
r"^(?:1?[012]|[0-9]):[0-5][0-9]\s*(?:am|pm)$"i