[Fixed]-Django template tag to convert epoch time to human readable time

0๐Ÿ‘

โœ…

I ended up going for something different โ€“ that avoids chaining and such in my template:

from django.template.defaulttags import register
import time

@register.filter(name='human_time')
def human_time(value):
    try:
        diff = time.time() - float(value)
    except:
        return ''
    m, s = divmod(diff, 60)
    h, m = divmod(m, 60)
    if h:
        return "%s hours ago" % int(h)
    elif m:
        return "%s minutes ago" % int(m)
    elif s:
        return "%s seconds ago" % int(s)

This can be naturally extended to cater for days, weeks, months and even years.

๐Ÿ‘คHassan Baig

1๐Ÿ‘

Sounds like something you should be doing before you get to the template. Just convert the timestamp to datetime object before you pass it in and use it as you would.

But if you insist:

from datetime import datetime
from django import template

register = template.Library()

@register.filter("parsetimestamp")
def timestamp(value):
    try:
        return datetime.fromtimestamp(value)
    except AttributeError, e:
        catch errors..

then use chaining in your template:

{{ your_time_stamp | parsetimestamp | timeuntil }}

Not tested but you should get the idea.

๐Ÿ‘คMarZab

Leave a comment