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?
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
You can try remove the microseconds from the timedelta object, before sending it to the template:
time = time - datetime.timedelta(microseconds=time.microseconds)
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With