Timedelta constructor with string parameter
felipou at gmail.com
felipou at gmail.com
Tue Sep 23 05:11:23 EDT 2014
Hello everyone!
I created some code recently to parse a string and create a timedelta from it.
Right now it only accepts positive integers, and only hours, minutes and seconds, but I think it could be easily extended to support everything that timedelta accepts.
time_delta_regex = re.compile(
r'((?P<hours>\d+?)h)?((?P<minutes>\d+?)m)?((?P<seconds>\d+?)s)?' )
def parseTimeDelta( value ):
timedelta_params = value
if isinstance( value, basestring ):
parts = time_delta_regex.match( value )
if not parts:
return None
parts = parts.groupdict()
timedelta_params = {}
for ( name, param ) in parts.iteritems():
if param:
timedelta_params[ name ] = int( param )
return datetime.timedelta( **timedelta_params )
parseTimeDelta("5h32m15s")
I was thinking this conversion could be very useful to lots of people, and so I thought about proposing it as an enhancement to the standard library.
But before doing anything, I thought it would be a good idea to see what people here think.
I think this would be a nice addition as a constructor of the timedelta class, but I'm not sure if it would conflict with any existing code. I can't see any downside to including this in the constructor or as a separate function.
So, what do you guys think?
More information about the Python-list
mailing list