1

这段代码一直给我错误。我的 Django 模型中有一个字段(日期时间),invite_sent同一个模型中的另一个字段称为check_timeCheck time 是invite sent应该发生某个操作之后的时间量。出于某种原因,我的代码无法正常工作。

模型.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)

视图.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)
4

1 回答 1

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
于 2012-12-28T10:09:52.933 回答