In my application,I am getting time input in a variable in string format e.g. Values = '12,12,12'.
Now i need to validate it h<24 M<60 S<60 etc. and i want final output in '%H:%M:%S' format.
To get this i tried datetime.time().
I had 1st tried with values = '12' then '12,12,12'.
In [1]: import datetime
In [2]: values = '12'
In [3]: d = datetime.time(values)
TypeError Traceback (most recent call last)
/mypc/test/<ipython console> in <module>()
TypeError: an integer is required
In [4]: d = datetime.time(int(values))
In [5]: d
Out[5]: datetime.time(12, 0)
In [6]: d.strftime('%H:%M:%S')
Out[6]: '12:00:00'
In [7]: s = d.strftime('%H:%M:%S')
In [8]: s
Out[8]: '12:00:00'
In [9]: values = '12,12,12'
In [10]: d = datetime.time(int(values))
ValueError: invalid literal for int() with base 10: '12,12,12'
But it works as below.
In [24]: datetime.time(12,12,12).strftime('%H:%M:%S')
Out[24]: '12:12:12'
So problem is that datetime.time() is taking input as integer and '12,12,12' string cannot be converted in int.
Is there any other way(otherthan regexp) to do the validation for only Hr:M:S.
You have to unpack the values:
This last statement will raise an error if the time given is invalid.
To avoid problems with zero-padded numbers, as “wim” pointed, it’s possible to change the second line to:
or