检测自Django模型中的日期以来是否已经过了设定时间

时间:2012-12-28 09:52:18

标签: python django datetime models

此代码一直给我错误。我的Django模型中有一个名为invite_sent的字段(日期时间)和同一模型中另一个名为check_time的字段。检查时间是invite sent之后应该发生某个操作的时间。出于某种原因,我的代码无法工作。

models.py

class Game(models.Model):
    title = models.CharField(max_length=50)
    summery = models.CharField(max_length=500)
    pin = models.CharField(max_length=12)
    key = models.CharField(max_length=12)
    complete = models.BooleanField()
    invite_sent = models.DateTimeField() #<-----------
    check_time = models.IntegerField() #<-----------
    on = models.ForeignKey("Member", related_name="turn", blank=True,  null=True)

views.py

def check_time():
    games = Game.objects.filter(complete = False)
    for g in games:
        hours = (datetime.datetime - g.invite_sent)/60/60 # trying to get hours between now and then
        if not hours > g.check_time: #stuff beyond this is not really important to the issue
            continue
        send_overtime(g)
        set_on(g)
        send_invite(g)

1 个答案:

答案 0 :(得分:4)

您在此行hours = (datetime.datetime - g.invite_sent)/60/60

时遇到问题
  • 您应该使用datetime.datetime.now()代替datetime.datetime(您必须调用的模块对象.now()
  • 减去两个datetime个对象会产生一个timedelta个对象,其方法.total_seconds()使用该对象转换为小时

因此有问题的代码应该是:

hours = (datetime.datetime.now() - g.invite_sent.replace(tzinfo=None)).total_seconds() / 60 / 60