validate string representation of a timedelta
Thomas Jollans
thomas at jollans.com
Tue Jun 29 08:00:56 EDT 2010
On 06/29/2010 03:41 AM, CM wrote:
> I'm looking for a good way to check whether a certain string is
> valid. It is a string representation of a Python timedelta object,
> like this: '0:00:03.695000'
>
> (But the first place, the hours, could also be double digits)
>
> In trying to figure out how to validate that, I saw this page which
> creates a parseTimeDelta(s) function, which takes that kind of string
> and returns a timedelta object:
>
> http://kbyanc.blogspot.com/2007/08/python-reconstructing-timedeltas-from.html
> (and I agree that this sort of function should come standard with
> datetime)
>
> I modified the code to accept microseconds, too, and I can use it now
> by trying to parse my candidate string and if it throws an exception,
> rejecting that string as invalid. It works fine on strings that are
> not even close to my format, like '0 min'. But it doesn't throw an
> exception on something like: '0:00:03.695000extrajunk'
>
> I'd like it to be pickier than that with the validation and only
> accept strings which are truly string representations of timedelta
> objects. But I have not learned regex yet, so am not sure how to
> modify parseTimeDetla so it wouldn't work with
> '0:00:03.695000extrajunk'.
>
> My question: is there a simple way to modify the parseTimeDelta so
> that it will work ONLY with a string that would be the string
> representation of a timedelta object?
If you want the end of the regexp to correspond to the end of the
string, add a "$" at the end of the regexp.
>
> Alternately, is there an easier/more Pythonic approach to validate
> this kind of string?
>
Or you could do something along the lines of:
shrs, smins, ssecs = s.split(':')
# convert, do things.
— Thomas
More information about the Python-list
mailing list