I am trying to extend the Python datetime.timedelta
for use with cross country race results. I want to construct an object from a string in format u\"mm:s
Apparently timedelta
objects are immutable, which means their value is actually set in the class' __new__()
method—so you'll need to override that method instead of its __init__()
:
import datetime
import re
class RaceTimedelta(datetime.timedelta):
def __new__(cls, timestr=''):
m = re.match(r'(\d+):(\d+\.\d+)', timestr)
if m:
mins, secs = int(m.group(1)), float(m.group(2))
return super(RaceTimedelta, cls).__new__(cls, minutes=mins, seconds=secs)
else:
raise ValueError('timestr argument not in format "mm:ss.d"')
print RaceTimedelta(u'24:45.7')
Output:
0:24:45.700000
BTW, I find it odd that you're providing a default value for thetimestr
keyword argument that will be considered illegal and raise aValueError
.