sinθ
sinθ

Reputation: 11483

Detecting if set time has elapsed since date in Django model

This code just keeps giving me errors. I have a field (datetime) in my Django model called invite_sent and another field in the same model called check_time Check time is the amount of time after invite sent that a certain action should occur. For some reason, my code wont work.

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)

Upvotes: 1

Views: 645

Answers (1)

Aamir Rind
Aamir Rind

Reputation: 39649

You have problems at this line hours = (datetime.datetime - g.invite_sent)/60/60

  • you should use datetime.datetime.now() instead of datetime.datetime (its a module object you have to call .now())
  • subtracting two datetime objects gives a timedelta objects which has a method .total_seconds() use that to convert to hours

so the buggy line of code should be:

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

Upvotes: 4

Related Questions