get elapsed time in django

0

I am creating a task in Django where I need to take all the orders and check the creation date to see how much time has elapsed, in case 2 days have passed to execute a code and in case 4 have passed, execute a different one.

Right now my model is like this:

class Pedido(models.Model):
    id = models.CharField(primary_key=True, max_length=9, editable=False)
    fecha = models.DateTimeField(auto_now_add = True)
    precio_producto = models.DecimalField(max_digits=12,decimal_places=2)
    precio_envio = models.DecimalField(max_digits=6,decimal_places=2)
    nom_producto = models.CharField(max_length = 40)
    talla = models.CharField(max_length = 5)
    marca = models.CharField(max_length = 20)

the code that I have right now is like this:

pedidos = Pedido.objects.all()
for p in pedidos:
    tiempo_transcurrido = date.today() - p.fecha
    if tiempo_transcurrido == timedelta(days=2):
        pass
    elif tiempo_transcurrido == timedelta(days=4):
        pass
    elif tiempo_transcurrido == timedelta(days=5):
        pass

The server returns this error:

  

days = date.today () - p.f_ped   TypeError: unsupported operand type (s) for -: 'datetime.date' and 'datetime.datetime'

    
asked by F Delgado 14.03.2018 в 08:48
source

1 answer

1

The problem is that python has two ways to get the current date. One is through datetime.date.today() and the other through datetime.datetime.today() . The first one returns an object of type datetime.date , while the second one returns an object of type datetime.datetime (which in addition to the date includes the exact time). Juan In your code (second fragment) you use an object of type datetime.date , while django retrieves the date from the database as type datetime.datetime , and both can not be subtracted, because the first does not have the time.

Use your code datetime.datetime.today() to get the current date.

Update . According to a user comment, the previous solution still gives problems. In this case it is because the date-time stored in the Django database includes the time zone ( timezone ), while the one obtained with datetime.datetime.today() by default does not have it.

The solution: use datetime.datetime.now() instead of today() , since this allows you to incorporate information about the time zone, which I will assume is utc (another problem will be dealing with different time zones).

from datetime import timezone
ahora = datetime.datetime.now(timezone.utc)
    
answered by 14.03.2018 / 12:00
source