文字列が "hh:mm" 時間形式の場合に True を返す関数があるかどうか知りたいですか? 自分で関数を書くこともできますが、標準関数があればいいのですが。
よろしくお願いします
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
使用できます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