When using the Steven B.'s solution, it throws a TypeError exception ('>=' not supported between instances of 'datetime.datetime' and 'float').
from django.db import models
from django.utils import timezone
import datetime
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
def was_published_recently(self):
return self.pub_date >= (datetime.datetime.now() - datetime.timedelta(days=1)).timestamp()
So when comparing datetimes in Django, we have to keep in mind that the datetime object is naive in Python by default, so you need to make both of them either naive or aware datetime objects. All credit to Viren Rajput in this answer
Because of that, the following solution works correctly:
from django.db import models
from django.utils import timezone
import datetime
import pytz
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
def was_published_recently(self):
return self.pub_date >= (timezone.now() - datetime.timedelta(days=1)).replace(tzinfo=pytz.UTC)
Note: If we cast both expressions to float using the timestamp() method:
from django.db import models
import datetime
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
def was_published_recently(self):
return self.pub_date.timestamp() >= (datetime.datetime.now() - datetime.timedelta(days=1)).timestamp()
(It could work, but PyCharm would point out the warning Unresolved attribute reference 'timestamp' for class 'DateTimeField')
Django version: 3.2.5