validate string representation of a timedelta

CM cmpython at gmail.com
Mon Jun 28 21:41:28 EDT 2010


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?

Alternately, is there an easier/more Pythonic approach to validate
this kind of string?

Thanks for any suggestions.
Che



More information about the Python-list mailing list