Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #78202
| Newsgroups | comp.lang.python |
|---|---|
| Date | 2014-09-23 02:11 -0700 |
| Message-ID | <a63a4890-eeb3-495c-bb81-3c1bbb85bff2@googlegroups.com> (permalink) |
| Subject | Timedelta constructor with string parameter |
| From | felipou@gmail.com |
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?
Back to comp.lang.python | Previous | Next — Next in thread | Find similar | Unroll thread
Timedelta constructor with string parameter felipou@gmail.com - 2014-09-23 02:11 -0700 Re: Timedelta constructor with string parameter Skip Montanaro <skip@pobox.com> - 2014-09-23 11:39 -0500 Re: Timedelta constructor with string parameter Felipe Menezes Machado <felipou@gmail.com> - 2014-09-23 19:15 +0200
csiph-web