pythondjangodjango-views

Convert UTC to local time zone in 'Views'


I'm retrieving data from database and sending it in JSON to the front end. Now the time is stored as UTC in database, so I want to change the timezone and its formatting before I send the data in JSON to front end. Changing/converting the time in front end is not an option.

What should I be doing? I am able to convert to appropriate timezone and formatting in Templates. However I want to do it now in views.

def fetchinfo(request):
    uid = int(request.user.id)
    data =                                                                                                                          UserLog.objects.filter(user_id=uid).values('event_id__description','time','ip_address')
    return JsonResponse({'status':'success','data':list(data),})

Solution

  • I created this little function to solve the problem in a project:

    import pytz
    from django.utils import timezone
    
    
    def convert_to_localtime(utctime):
      fmt = '%d/%m/%Y %H:%M'
      utc = utctime.replace(tzinfo=pytz.UTC)
      localtz = utc.astimezone(timezone.get_current_timezone())
     return localtz.strftime(fmt)
    

    An used like:

    utcdate = convert_to_localtime(date_from_db)
    

    I also installed this app: django-tz-detect