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),})
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.
Use the datetime. datetime. now() to get the current date and time. Then use tzinfo class to convert our datetime to UTC.
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
I had the same problem... interestingly this solution didn't work for me, here's my working version:
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With