简体   繁体   English

我如何比较时区和日期时间的实例

[英]how can i compare instances of timezone and datetime

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我在 django 中创建了一个 todo 模型,使用了一种清除旧 todo 的方法,该方法应该删除 24 小时前发布的 todo,我似乎无法在 if 条件下比较日期时间和时区实例

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.减去一个datetimedatetime给你一个timedelta ,两个时间之间的区别。 Subtracting a timedelta from a datetime gives you a datetime , a new timestamp different from the first by the amount of the timedelta .datetime减去timedelta会给你一个datetime ,一个新的时间戳,与第一个不同,时间为timedelta的量。

In timezone.now()-todo.pub_date , you're subtracting two datetime .timezone.now()-todo.pub_date ,您减去两个datetime
In timezone.now()-time_limit , you're subtract a timedelta from a datetime .timezone.now()-time_limit ,您将从datetime减去timedelta

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 .要么想做timezone.now() - todo.pub_date以生成timedelta并检查该timedelta是否> / <某个特定值(即比较两个timedelta s),要么您想做timezone.now() - time_limit生成过去的datetime时间并检查它是否是> / <您的todo.pub_date datetime

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM