The Python Oracle

python time format check

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Techno Intrigue Looping

--

Chapters
00:00 Question
00:26 Accepted answer (Score 30)
00:43 Answer 2 (Score 5)
00:58 Answer 3 (Score 3)
01:11 Answer 4 (Score 3)
01:37 Thank you

--

Full question
https://stackoverflow.com/questions/1322...

Answer 2 links:
[http://regexlib.com/DisplayPatterns.aspx...]: http://regexlib.com/DisplayPatterns.aspx...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #regex

#avk47



ACCEPTED ANSWER

Score 31


You can achieve this without regular expressions:

import time

def isTimeFormat(input):
    try:
        time.strptime(input, '%H:%M')
        return True
    except ValueError:
        return False

>>>isTimeFormat('12:12')
True

>>>isTimeFormat('012:12')
False



ANSWER 2

Score 7


import re

time_re = re.compile(r'^(([01]\d|2[0-3]):([0-5]\d)|24:00)$')
def is_time_format(s):
    return bool(time_re.match(s))

Matches everything from 00:00 to 24:00.




ANSWER 3

Score 3


This will give you the regexp object which will check it. However, depending on who you ask 24:00 might not be a valid time (it's 00:00). But I guess this is easy to modify to suit your needs.

import re
regexp = re.compile("(24:00|2[0-3]:[0-5][0-9]|[0-1][0-9]:[0-5][0-9])")



ANSWER 4

Score 3


This pattern should help you:

http://regexlib.com/DisplayPatterns.aspx?cattabindex=4&categoryId=5