python时间格式检查

7 python regex

在python,我想检查输入字符串是否在"HH:MM"中,例如01:16或23:16或24:00.结果是真还是假.

如何通过使用正则表达式实现此目的?

Nad*_*mli 23

你可以在没有正则表达式的情

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
Run Code Online (Sandbox Code Playgroud)


Ant*_*sma 6

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))
Run Code Online (Sandbox Code Playgroud)

匹配从 00:00 到 24:00 的所有内容。