Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I compare dates in Django?

Tags:

python

django

I have a Django model class with a class variable due_date:

due_date = models.DateField()

I want to output in the Django admin if the object is due or not based on today's date.

My function is as follows:

def is_due_today(self):
    dd = self.due_date
    today = datetime.date.now
    return dd - today > 0

But my output is:

(None)

What am I doing wrong?

like image 231
ChrisC Avatar asked Nov 23 '25 12:11

ChrisC


1 Answers

Subtracting two datetime objects in Python gives you a timedelta object, which you can't compare to an integer. You can, however, get something like total_seconds() from it to see if it's nonzero.

>>> now = datetime.datetime.now()
# wait 3 seconds
>>> now2 = datetime.datetime.now()
>>> td = now2 - now
>>> td.total_seconds()
3.266

So in your case, the code would look something like (untested):

def is_due_today(self):
    dd = self.due_date
    delta = dd - datetime.date.today()
    return delta.total_seconds() > 0
like image 75
Daniel DiPaolo Avatar answered Nov 28 '25 15:11

Daniel DiPaolo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!