The Python Oracle

python time format check

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: RPG Blues Looping

--

Chapters
00:00 Python Time Format Check
00:22 Accepted Answer Score 31
00:36 Answer 2 Score 3
00:55 Answer 3 Score 7
01:08 Answer 4 Score 3
01:15 Thank you

--

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

--

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