How to make math with datetime inside models?

Viewed 22

I'v been trying to add 10 days in a django model.

I want to make this everytime a data is created in the DB.

expiration = 10
expiration_at = date of creation + expiration

example

EDITED

After some codes from comments. I got this so far.

class Certificados(models.Model):
username = models.CharField(max_length=30, unique=True, null=False)
name = models.CharField(max_length=255, null=False)
description = models.TextField(null=True)
created_at = models.DateTimeField(auto_now=True)
updated_at = models.DateTimeField(auto_now=True)
expiration = models.PositiveIntegerField()
expiration_at = models.DateTimeField()

def save(self, *args, **kwargs):
   self.expiration_at = self.created_at + timedelta(days=self.expiration)

class Meta:
    db_table = 'Certificados'
    
def __str__(self):
    return self.username

This code now brings me this error. Error Someone knows what is wrong?

2 Answers

For this you'll want to use timedelta() from the datetime package.

from datetime import timedelta

expiration = timedelta(days=10)
expiration_at += expiration

Another approach could be to use the arrow package:

Arrow is a Python library that offers a sensible and human-friendly approach to creating, manipulating, formatting and converting dates, times and timestamps.

One way to achieve this in arrow would be with arrow.utcnow().shift(days=10).datetime. Notice I'm using utcnow() here; this is because working with any other date timezone will lead to massive headaches, so I'd recommend working with UTC if you can :). If you need a specific timezone, I'd recommend reading the arrow docs to learn more.

If you want the expiration time to be adjustable post-creation, you'd need to save the creation time too.

You can then derive the expiry time in e.g. save():

import datetime
from django.utils.timezone import now


class Thing(models.Model):
    creation_time = models.DateTimeField(default=now)
    expiry_days = models.PositiveIntegerField(default=10)
    expiry_time = models.DateTimeField()

    def save(self, *args, **kwargs):
        self.expiry_time = self.creation_time + datetime.timedelta(days=self.expiry_days)
        super().__save__(*args, **kwargs)
Related