Home > Mobile >  How to render the timedelta of a Django datetime field vs. now?
How to render the timedelta of a Django datetime field vs. now?

Time:09-22

I do have a Model Vote that contains a DateTimeField which returns
the date in the template like so: Sept. 22, 2021, 10:02 a.m.

# Model

class Vote(models.Model):

    created_on = models.DateTimeField(auto_now_add=True)

I now want to render the time delta between now and the time stored in the Model in the template:

# Template

<div> voted {{ vote.created_on|datetime_delta }} ago</div>

Should render for example: voted 16 hours ago or voted 3 days ago

As far as I know there is no built-in solution to this in Django, thus I tried to create an individual template filter:

# Template filter

from django import template
import datetime

register = template.Library()

# Output Django:         Sept. 22, 2021, 10:02 a.m.
# Output datetime.now(): 2021-09-22 12:56:57.268152

@register.filter(name='datetime_delta')
def datetime_delta(past_datetime):
    datetime_object = datetime.datetime.now().strftime("%bt. %d, %Y, %H:%M %p")
    print(datetime_object) # prints Sept. 22, 2021, 13:20 PM

So I somehow tried to create two time objects in the same structure to calculate the time delta but can't make it fit 1:1. Anyways, I don't know if this might be a working approach and neither do I know if there are smarter solutions to this?

CodePudding user response:

Django already has a |naturaltime template filter [Django-doc]. You can use this with:

# Template

{% load humanize %}

<div> voted {{ vote.created_on|naturaltime }}</div>
  • Related