DurationField format

I have a DurationField defined in my model as

day0 = models.DurationField('Duration for Monday', default=datetime.timedelta)

When I try to view this, I want it formatted as "HH:MM" -- It is always less than 24. So, I tried these in the HTML template file:

{{ slice.day0|time:'H:M' }}
{{ slice.day0|date:'H:M' }}

However, all I get is an empty space.

What am I doing wrong?

Upvotes: 7

Views: 3701

Answers (2)

For posterity: here is what I used in the end. This is the content of <app>/templatetags/datetime_filter.py:

# -*- coding: utf-8 -*-
"""Application filter for `datetime`_ 24 hours.

.. _datetime: https://docs.python.org/2/library/datetime.html
"""

from django import template
from datetime import date, timedelta

register = template.Library()

@register.filter(name='format_datetime')
def format_datetime(value):
    hours, rem = divmod(value.seconds, 3600)
    minutes, seconds = divmod(rem, 60)
    return '{}h {}m'.format(hours, minutes)

Then in the view, add this:

{% load datetime_filter %}
[...]
{{ slice.day0|format_datetime }}

Upvotes: 5

Alasdair
Alasdair

Reputation: 308869

A timedelta instance is not a time or a datetime. Therefore it does not make sense to use the time or date filters.

Django does not come with any template filters to display timedeltas, so you can either write your own, or look for an external app that provides them. You might find the template filters in django-timedelta-field useful.

Upvotes: 8

Related Questions