Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying a timedelta object in a django template

I'm having trouble getting my django template to display a timedelta object consistently. I tried using the time filter in my template, but nothing is displayed when I do this. The timedelta object is shown as follows on the errors page if I use Assert False:

time    datetime.timedelta(0, 38, 132827)

This displays the time difference as:

0:00:38.132827

I would like to only show the hours, minutes, and seconds for each timedelta object. Does anyone have any suggestions on how I can do this?

like image 526
bgmaster Avatar asked May 02 '13 21:05

bgmaster


3 Answers

I followed Peter's advice and wrote a custom template filter.

Here's the steps I took.

First I followed this guide to create a custom template filter.

Be sure to read this section on code layout.

Here's my filter code

from django import template

register = template.Library()

@register.filter()
def smooth_timedelta(timedeltaobj):
    """Convert a datetime.timedelta object into Days, Hours, Minutes, Seconds."""
    secs = timedeltaobj.total_seconds()
    timetot = ""
    if secs > 86400: # 60sec * 60min * 24hrs
        days = secs // 86400
        timetot += "{} days".format(int(days))
        secs = secs - days*86400

    if secs > 3600:
        hrs = secs // 3600
        timetot += " {} hours".format(int(hrs))
        secs = secs - hrs*3600

    if secs > 60:
        mins = secs // 60
        timetot += " {} minutes".format(int(mins))
        secs = secs - mins*60

    if secs > 0:
        timetot += " {} seconds".format(int(secs))
    return timetot

Then in my template I did

{% load smooth_timedelta %}

{% timedeltaobject|smooth_timedelta %}

Example output

enter image description here

like image 151
chidimo Avatar answered Nov 10 '22 11:11

chidimo


You can try remove the microseconds from the timedelta object, before sending it to the template:

time = time - datetime.timedelta(microseconds=time.microseconds)
like image 44
lonemc Avatar answered Nov 10 '22 11:11

lonemc


I don't think there's anything built in, and timedeltas don't directly expose their hour and minute values. but this package includes a timedelta custom filter tag that might help: http://pydoc.net/django-timedeltafield/0.7.10/

like image 2
Peter DeGlopper Avatar answered Nov 10 '22 13:11

Peter DeGlopper