79111136

Date: 2024-10-21 17:33:50
Score: 0.5
Natty:
Report link

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
from datetime import datetime

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".

Reasons:
  • Long answer (-1):
  • No code block (0.5):
  • Low reputation (1):
Posted by: Rishav Shahil