简体   繁体   English

如何验证时间格式?

[英]How to validate time format?

This is what I have so far, it probably is completely junk. 这就是我到目前为止,它可能完全是垃圾。 What I want to do is validate caminput1 , so that the format is HH:MM:SS . 我想要做的是验证caminput1 ,以便格式为HH:MM:SS

The hashes are from when I was testing. 哈希是从我测试时开始的。

def cameraspeedcheck():
    timeformat = ("%H:%M:%S")
    caminput1 = input("At what time did sensor 1 actuate? ")

    # is caminput1 = time(HH:MM:SS)
    # time.strptime(caminput1[%H:%M:%S])

    caminput1.strptime(timeformat)
    # else cameraspeedcheck()

I am not very experienced with the syntax of all this stuff, or coding in general, but before you tell me to go and look it up. 我对所有这些东西的语法,或者一般的编码都不是很有经验,但在你告诉我去查阅它之前。

I have been looking around for ages, and I cannot find anything that explains the whole process. 我一直在四处寻找,我找不到任何解释整个过程的东西。

strptime is a class-method of datetime.datetime which accepts the string to parse as first argument and the format as the second argument. strptimedatetime.datetime的类方法,它接受要解析为第一个参数的字符串,并将格式作为第二个参数。 So you should do - 所以你应该这样做 -

def cameraspeedcheck():
    timeformat = "%H:%M:%S"
    caminput1 = input("At what time did sensor 1 actuate? ")
    try:
        validtime = datetime.datetime.strptime(caminput1, timeformat)
        #Do your logic with validtime, which is a valid format
    except ValueError:
        #Do your logic for invalid format (maybe print some message?).

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM