Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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.

like image 697
Appel Avatar asked Oct 12 '15 08:10

Appel


People also ask

How do I validate a time string format in Python?

") 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?).


1 Answers

strptime is a class-method of datetime.datetime which accepts the string to parse as first argument and the format as the second argument. 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?).
like image 86
Anand S Kumar Avatar answered Oct 15 '22 14:10

Anand S Kumar