Django:将UTC转换为"视图"中的本地时区

the*_*arl 3 django django-views

我正在从数据库中检索数据并将其发送到json到前端.现在时间在UTC中存储为数据库,所以我想在将数据发送到前端之前更改时区及其格式.改变/转换前端的时间不是一种选择.

我该怎么办?

注意:我可以在模板中转换为适当的时区和格式.但是我现在想在视图中这样做.

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),})

Mar*_*ndi 9

from django.utils import timezone

local_dt = timezone.localtime(date_from_db) if date_from_db is not None else None
Run Code Online (Sandbox Code Playgroud)


jak*_*bdo 8

我创建了这个小函数来解决项目中的问题:

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)
Run Code Online (Sandbox Code Playgroud)

用过的像:

utcdate = convert_to_localtime(date_from_db)
Run Code Online (Sandbox Code Playgroud)

我还安装了这个应用程序:django-tz-detect