Python 如何要求用户输入时间

Python 如何要求用户输入时间,python,input,time,Python,Input,Time,在Python中,如何要求用户输入时间,然后将答案验证为正确的时间格式 while True: try: TimeInput = input("What time is it now ? :") ValidTime = ??????????????????????????????????? print (ValidTime) break except ValueError: print ("Use

在Python中,如何要求用户输入时间,然后将答案验证为正确的时间格式

while True:
    try: 
        TimeInput = input("What time is it now ? :")
        ValidTime = ???????????????????????????????????
        print (ValidTime)
        break 
    except ValueError:
        print ("Use Format Hours: Minutes (HH:MM)")
该功能可能会对您有所帮助。如果输入文本不是好的日期时间,它将引发异常。 导入日期时间

def get_input_time():
    while True:
        input = raw_input("What time is it now?\n")
        try: # strptime throws an exception if the input doesn't match the pattern
            input_time = datetime.datetime.strptime(input, "%H:%M")
            break
        except:
            print("Use Format Hours:Minutes (HH:MM)")
    return input_time

#test the function
input_time = get_input_time()
print("Time is %s:%s" % (input_time.hour, input_time.minute))

太棒了,谢谢!然而,我不得不用inout替换原始输入