djangodjango-templates

Format of timesince filter


Is there a way to use the {{date|timesince}} filter, but instead of having two adjacent units, only display one?

For example, my template is currently displaying "18 hours, 16 minutes". How would I get it to display "18 hours"? (Rounding is not a concern here.) Thank you.


Solution

  • The built-in {{ date|timesince }} displays two adjacent units (like "18 hours, 16 minutes") by default, but we can override this behavior

    1. Steps to create a custom template filter: Create a custom filter in your Django app:

    Inside one of your apps, create a new file (if it doesn't exist yet) called templatetags/custom_filters.py:

    your_app/
        templatetags/
            __init__.py  # Make sure this exists
            custom_filters.py
    

    Define the custom timesince_single_unit filter:

    In custom_filters.py, you can create a new filter to modify the behavior of timesince:

    from django import template
    from django.utils.timesince import timesince
    
    register = template.Library()
    
    @register.filter
    def timesince_single_unit(value):
        """
        Custom timesince filter to show only the first unit (like '18 hr' or '16 min').
        """
        if not value:
            return ""
        
        # Get the full timesince output (e.g., "18 hours, 16 minutes")
        time_str = timesince(value)
        
        # Split by the comma and keep only the first unit
        first_unit = time_str.split(",")[0]
        
        # Optionally, abbreviate 'hours' to 'hr' and 'minutes' to 'min'
        first_unit = first_unit.replace("hours", "hr").replace("minutes", "min")
        
        return first_unit
    

    Load the custom filter in your template:

    To use your new filter, first load it in the template where you want to display the time in the desired format.

    In your template file:

    {% load custom_filters %}
    
    {{ your_date_value|timesince_single_unit }}
    

    Example Output: If the difference is 18 hours and 16 minutes, it will display: "18 hr". If the difference is 16 minutes, it will display: "16 min".