Search code examples
pythondatetimemonkeypatchingpython-datetime

Monkey patching 'datetime' produces strange results


I'm trying to make one of my libraries compatible with Python 2.6. It uses the method datetime.timedelta.total_seconds which was added in 2.7, so to make it work with 2.6, I wanted to monkey patch it into timedelta like this:

import datetime

if not hasattr(datetime.timedelta, 'total_seconds'):

    class timedelta(datetime.timedelta):
        def total_seconds(self):
            return self.days * 86400.0 + self.seconds + self.microseconds * 1e-6

    datetime.timedelta = timedelta

This does actually work in some cases, e.g. if I create a timedelta variable, it does have this method. But if a new timedelta object is produced by subtracting two datetime.datetime values, the method is missing from the resulting object.

What's going wrong and how do I fix this?


Solution

  • The datetime module is written entirely in C.

    This includes the function that subtracts one datetime.datetime object from another. That function -- called new_delta() -- directly instantiates PyDateTime_DeltaType, which is the original datetime.timedelta class (written in C). It won't notice that you've rebound datetime.timedelta to your own class in Python-land.

    I don't see any easy workarounds.