How to extend datetime.timedelta?

后端 未结 1 1647
遇见更好的自我
遇见更好的自我 2020-12-21 02:23

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

相关标签:
1条回答
  • 2020-12-21 03:08

    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 thetimestrkeyword argument that will be considered illegal and raise aValueError.

    0 讨论(0)
提交回复
热议问题