Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django : 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?

Note: 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),})
like image 215
theblackpearl Avatar asked Nov 08 '14 01:11

theblackpearl


People also ask

How do I convert UTC time to local time in Django?

How do you convert UTC time to local time in Python? Create a datetime object from the UTC time string. This datetime object will have no timezone associated with it. Convert the timezone of the datetime object to local timezone by calling the astimezone() function on datetime object.

How do you convert UTC to time in Python?

Use the datetime. datetime. now() to get the current date and time. Then use tzinfo class to convert our datetime to UTC.


2 Answers

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

like image 144
jakobdo Avatar answered Sep 21 '22 11:09

jakobdo


I had the same problem... interestingly this solution didn't work for me, here's my working version:

(In settings.py USE_L10N = False, and USE_TZ = False)

import pytz import tzlocal

def convert_to_localtime(utc):
  fmt = '%d/%m/%Y %H:%M'
  ltz = tzlocal.get_localzone()
  localtz = utc.replace(tzinfo=pytz.utc).astimezone(ltz)
  return localtz.strftime(fmt)
like image 20
Sütemény András Avatar answered Sep 22 '22 11:09

Sütemény András