此代码一直给我错误。我的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)
答案 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