i created a todo model in django with a method of clear old todo that is supposed to delete todos that were published more than 24 hours ago, i can't seem to be able to compare datetime and timezone instances in my if condition
class Todo(models.Model):
description = models.CharField(max_length=200)
Todo_date = models.DateTimeField('Todo Date')
pub_date = models.DateTimeField('Date Published')
def __str__(self):
return self.description
def create_todo(self, description, Todo_date, pub_date):
todo = Todo(description=description,
Todo_date=Todo_date, pub_date=pub_date)
todo.save()
return todo
def delete_todo(self, description):
todo = Todo.objects.get(description=description)
todo.delete()
return "Todo removed"
def clear_old_todo(self):
todos = Todo.objects.all()
time_limit = datetime.timedelta(hours=24)
for todo in todos:
if (timezone.now()-todo.pub_date) > (timezone.now()-time_limit):
todo.delete()
return "old todo cleared"
>>> Todo.clear_old_todo("self")
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "E:\projects\1stDjangoApp\ToDoList\ToDo\models.py", line 36, in clear_old_todo
if (timezone.now()-todo.pub_date) > (timezone.now()-time_limit):
TypeError: '>' not supported between instances of 'datetime.timedelta' and 'datetime.datetime'
Subtracting a datetime
from a datetime
gives you a timedelta
, the difference between the two times. Subtracting a timedelta
from a datetime
gives you a datetime
, a new timestamp different from the first by the amount of the timedelta
.
In timezone.now()-todo.pub_date
, you're subtracting two datetime
.
In timezone.now()-time_limit
, you're subtract a timedelta
from a datetime
.
You either want to do timezone.now() - todo.pub_date
to produce a timedelta
and check if that timedelta
is >
/ <
some specific value (ie compare two timedelta
s), or you want to do timezone.now() - time_limit
to produce a datetime
in the past and check whether that is >
/ <
your todo.pub_date
datetime
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.