如何要求用户输入tim

2024-09-28 23:06:49 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

Tags: 答案用户trueinputtimeis格式时间
1条回答
网友
1楼 · 发布于 2024-09-28 23:06:49

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

相关问题 更多 >