Question

I'd like to know if there is a function which returns True if a string is in "hh:mm" hour format? I can write my own function, but it would be good if there is a standard function.

Best Regards

Was it helpful?

Solution

Just try to interpret it using the time module, and catch the ValueError raised when the conversion fails:

>>> 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'

The only thing this doesn't check is that you actually specify the correct number of digits. Checking if len(time_string) == 5 might be simple enough to check that.

Edit: inspired by Kimvais in the comments; to wrap it as a function:

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

OTHER TIPS

You can use 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()).

To parse a time string that works:

>>> 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)

If you pass in a time string that is not valid, you will get an error:

>>> 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'

So... your function could look like this:

def is_hh_mm(t):
    try:
        time.strptime(t, '%H:%M')
    except:
        return False
    else:
        return True
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top