1

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

最好的祝福

4

2 回答 2

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
于 2012-02-08T09:12:04.470 回答
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
于 2012-02-08T09:15:07.607 回答