'How to workout if a datetime is older than x months in Python

I want to find out if a entry has been updated in the last 6 months.

This is what I have tried:

 def is_old(self):
        """
        Is older than 6 months (since last update)
        """
        time_threshold = datetime.date.today() - datetime.timedelta(6*365/12)
        if self.last_update < time_threshold:
            return False
        return True

but i get the error:

    if self.last_update < time_threshold:
TypeError: can't compare datetime.datetime to datetime.date


Solution 1:[1]

You need the days keyword

>>> import datetime
>>> datetime.date.today() - datetime.timedelta(days=30)
datetime.date(2014, 5, 26)
>>> datetime.date.today() - datetime.timedelta(days=180)
datetime.date(2013, 12, 27)
>>> datetime.date.today() - datetime.timedelta(days=6*365/12)
datetime.date(2013, 12, 25)

Also, coming to your actual error: TypeError: can't compare datetime.datetime to datetime.date

You can just do

def is_old(self):

    time_threshold = datetime.date.today() - datetime.timedelta(days=6*365/12)

    #The following code can be simplified, i shall let you figure that out yourself. 
    if self.last_update and self.last_update.date() < time_threshold:
        return False
    return True

Solution 2:[2]

Your database field last_update is datetime field and you are comparing it against date hence the error, Instead of datetime.date.today() use datetime.datetime.now(). Better use django.utils.timezone which will respect the TIME_ZONE in settings:

from django.utils import timezone

def is_old(self):
    """
    Is older than 6 months (since last update)
    """
    time_threshold = timezone.now() - datetime.timedelta(6*365/12)
    return bool(self.last_update > time_threshold)

Solution 3:[3]

You can use the external module dateutil:

from dateutil.relativedelta import relativedelta

def is_old(last_update):
    time_threshold = date.today() - relativedelta(months=6)
    return last_update < time_threshold

That's assuming the type of last_update is a date object

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Aamir Rind
Solution 3 Swier