Search code examples
djangodatetimedjango-filter

Django custom filter - to convert datetime


I am working on a Django app and need to show datetime on the UI. the datetime is UTC format and I need to convert it into local timezone of the user. for this I implemented this custom filter in my app

from django import template
import pytz

register = template.Library()

@register.filter
def convert_to_localtime(value, user_tz):
    if not value:
        return value
    
    local_tz = pytz.timezone(user_tz)
    local_time = value.astimezone(local_tz)
    print("Conversion function",value, local_time)
    return local_time

In the template I am using this custom filter like this

{%load custom_filters%}
<span class="text-center match-date-time">{{ match.start_time|convert_to_localtime:user_tz}}</span>

I can see that the custom filter is executing and converting datetime properly into local timezone as I can see following output for the print statement

Conversion function 2023-08-03 17:30:00+00:00 2023-08-03 23:00:00+05:30

But on the UI I still the UTC datetime rather than the converted time. What am I missing?


Solution

  • I think the problem is in showing converted time.

    Try this:

    {% load custom_filters %}
    
    <span class="text-center match-date-time">
        {{ match.start_time|convert_to_localtime:user_tz|date:"Y-m-d H:i:s" }}
    </span>
    

    Or try doing it in your function:

    from django import template
    import pytz
    
    register = template.Library()
    
    @register.filter
    def convert_to_localtime(value, user_tz):
        if not value:
            return value
        
        local_tz = pytz.timezone(user_tz)
        local_time = value.astimezone(local_tz)
        formatted_time = local_time.strftime('%Y-%m-%d %H:%M:%S')
        return formatted_time