我如何要求用户输入时间

时间:2018-12-01 01:20:10

标签: python input time

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

while True:
    try: 
        TimeInput = input("What time is it now ? :")
        ValidTime = ???????????????????????????????????
        print (ValidTime)
        break 
    except ValueError:
        print ("Use Format Hours: Minutes (HH:MM)")

1 个答案:

答案 0 :(得分:1)

strptime功能可能会对您有所帮助。如果输入文本的日期时间不好,则会引发异常。     导入日期时间

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))