Subclassing datetime: Is there a better way to maintain resulting object type after arithmetic operations?
<p>I recently ran into a situatiton where I needed to subclass <code>datetime.datetime</code> and <code>datetime.timedelta</code> in order to add a few methods.  I immediately found, though, that any arithmetic operations would return a <code>datetime.datetime</code> object when I expected it to return a <code>mydatetime.mydatetime</code> instance instead.  Below is the solution that a co-worker helped me out with for this problem.  Does anyone have a more concise or convenient suggestion?  Are there any dangers to what I have done here?  Am I missing anything important?</p>

<pre><code>from datetime import datetime, timedelta

def _to_mydatetime(native):
    '''Instantiates object of appropriate class based on class
    of the input object.'''
    if hasattr(native, 'timetuple'):
        return mydatetime(*native.timetuple()[:6])
    else:
        return mytimedelta(native.days, native.seconds)

class mydatetime(datetime):
    '''Subclass of datetime'''
    def __add__(self, other):
        result = super(mydatetime, self).__add__(other)
        return _to_mydatetime(result)

    def __sub__(self, other):
        result = super(mydatetime, self).__sub__(other)
        return _to_mydatetime(result)

class mytimedelta(timedelta):
    def __add__(self, other):
        result = super(mytimedelta, self).__add__(other)
        return _to_mydatetime(result)

    def __sub__(self, other):
        result = super(mytimedelta, self).__sub__(other)
        return _to_mydatetime(result)

    def __div__(self, other):
        result = super(mytimedelta, self).__div__(other)
        return _to_mydatetime(result)

    def __rmul__(self, other):
        result = super(mytimedelta, self).__rmul__(other)
        return _to_mydatetime(result)

    def __mul__(self, other):
        result = super(mytimedelta, self).__mul__(other)
        return _to_mydatetime(result)
</code></pre>
