如何判断python中的字符串是否为hh:mm格式?

时间:2012-02-08 09:09:03

标签: python function hour

我想知道如果字符串是“hh:mm”小时格式,是否有一个返回True的函数? 我可以编写自己的函数,但如果有标准函数会很好。

最好的问候

2 个答案:

答案 0 :(得分:5)

尝试使用time模块解释它,并捕获转换失败时引发的ValueError

>>> time.strptime('08:30', '%H:%M')
time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=8, tm_min=30, tm_sec=0, tm_wday=0, tm_yday=1, tm_isdst=-1)
>>> time.strptime('08:70', '%H:%M')
Traceback (most recent call last):
  (...)
ValueError: unconverted data remains: 0
>>> time.strptime('0830', '%H:%M')
Traceback (most recent call last):
  (...)
ValueError: time data '0830' does not match format '%H:%M'

唯一不检查的是您实际指定了正确的位数。检查len(time_string) == 5是否足够简单以检查它。

编辑:在评论中受到Kimvais的启发;把它包装成一个函数:

def is_hh_mm_time(time_string):
    try:
        time.strptime(time_string, '%H:%M')
    except ValueError:
        return False
    return len(time_string) == 5

答案 1 :(得分:2)

您可以使用time.strptime

>>> help(time.strptime)
Help on built-in function strptime in module time:

strptime(...)
    strptime(string, format) -> struct_time

    Parse a string to a time tuple according to a format specification.
    See the library reference manual for formatting codes (same as strftime()).

解析有效的时间字符串:

>>> time.strptime('12:32', '%H:%M')
time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=12, tm_min=32, tm_sec=0, tm_wday=0, tm_yday=1, tm_isdst=-1)

如果传入无效的时间字符串,则会收到错误:

>>> time.strptime('32:32', '%H:%M')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\_strptime.py", line 454, in _strptime_time
    return _strptime(data_string, format)[0]
  File "C:\Python27\lib\_strptime.py", line 325, in _strptime
    (data_string, format))
ValueError: time data '32:32' does not match format '%H:%M'

所以......你的功能看起来像这样:

def is_hh_mm(t):
    try:
        time.strptime(t, '%H:%M')
    except:
        return False
    else:
        return True