Display and format Django DurationField in template
No, I don't think there is any built in filter to format a timedelta
, it should be fairly easy to write one yourself though.
Here is a basic example:
from django import template
register = template.Library()
@register.filter
def duration(td):
total_seconds = int(td.total_seconds())
hours = total_seconds // 3600
minutes = (total_seconds % 3600) // 60
return '{} hours {} min'.format(hours, minutes)
Contribution for Aumo answer:
from django import template
register = template.Library()
@register.filter
def duration(td):
total_seconds = int(td.total_seconds())
days = total_seconds // 86400
remaining_hours = total_seconds % 86400
remaining_minutes = remaining_hours % 3600
hours = remaining_hours // 3600
minutes = remaining_minutes // 60
seconds = remaining_minutes % 60
days_str = f'{days}d ' if days else ''
hours_str = f'{hours}h ' if hours else ''
minutes_str = f'{minutes}m ' if minutes else ''
seconds_str = f'{seconds}s' if seconds and not hours_str else ''
return f'{days_str}{hours_str}{minutes_str}{seconds_str}'
This is the one I use, it rounds minutes and display only the information needed :
@register.filter
def duration(timedelta):
"""
Format a duration field
"2h and 30 min" or only "45 min" for example
:rtype: str
"""
total_seconds = int(timedelta.total_seconds())
hours = total_seconds // 3600
minutes = round((total_seconds % 3600) / 60)
if minutes == 60:
hours += 1
minutes = 0
if hours and minutes:
# Display both
return f'{hours}h and {minutes} min'
elif hours:
# Display only hours
return f'{hours}h'
# Display only minutes
return f'{minutes} min'