How to calculate the difference between now and a model DateTimeField for a Django app ?

Published: January 05, 2021

Tags: Python; Django; Protection Status

Examples of how to calculate the difference between now and a model DateTimeField for a Django app:

Confirmation email verification (Example 1)

Lets consider for example the following model which will be used when a new user signed up to our app and to verify if the email belongs to the user or not (

from datetime import datetime

class email_confirmation(models.Model):
    notebook = models.ForeignKey(Notebook, null=True, blank=True, default = None,on_delete=models.DO_NOTHING)
    secret_token = models.CharField(max_length=200,default='')
    date_created = models.DateTimeField(   
    removed = models.BooleanField(default=False)

The goal is to check if the confirmation to verify the user email has been sent less than two hours ago (i.e. 120 minutes ago). To do that:

from datetime import timezone

email_confirmation_obj = email_confirmation.objects.filter(secret_token=token, removed=False)[0]
delta = - email_confirmation_obj.date_created   
if (delta.seconds//60)%60  < 120:
    print('do something !')

Note: timezone.utc is used to avoid the error:

can't subtract offset-naive and offset-aware datetimes

Check the number of new entries (Example 2)

Another example using a filter to check the number of new articles created by users in the last hour (lets assume that less that 20 new articles created in one hour seems normal but more can be suspicious)

class Article(models.Model):
    date_created = models.DateTimeField(   

time_threshold = - datetime.timedelta(hours=1)
results = Article.objects.filter(date_created__gt=time_threshold)
if results.count() < 20:
    print('Looks ok  !')
    print('somehting wrong !')