[英]Django : Convert UTC to local time zone in 'Views'
I'm retrieving data from database and sending it in json to the front end.我正在从数据库中检索数据并将其以 json 格式发送到前端。 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.
现在时间在数据库中存储为 UTC,所以我想在将 json 中的数据发送到前端之前更改时区及其格式。 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),})
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我还安装了这个应用程序: django-tz-detect
from django.utils import timezone
local_dt = timezone.localtime(date_from_db) if date_from_db is not None else None
I had the same problem... interestingly this solution didn't work for me, here's my working version:我有同样的问题......有趣的是,这个解决方案对我不起作用,这是我的工作版本:
import pytz import tzlocal导入 pytz 导入 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)
You can used middleware for transform the datetime您可以使用中间件来转换日期时间
class Record(models.Model):
uuid = models.UUIDField(primary_key=True, default=uuid4, editable=False)
identification = models.CharField(max_length=255)
first_name = models.CharField(max_length=255)
created_at = models.DateTimeField(auto_now_add=True)
time_record = models.DateTimeField(
blank=False,
null=True,
)
class Meta:
verbose_name = "Record"
verbose_name_plural = "Records"
def __str__(self):
return f"{self.first_name} {self.last_name} id: {self.identification}"
from django.utils.timezone import activate
class TimezoneMiddleware(MiddlewareMixin):
def process_request(self, request):
hour = utc_header(request.headers.get("time", ""))
try:
activate("Etc/GMT" + hour)
except Exception:
activate("Etc/GMT")
class RecordSerializer(serializers.ModelSerializer):
class Meta:
model = Record
fields = "__all__"
class ListCreateRecordview(generics.ListCreateAPIView):
queryset = Record.objects.order_by(
"-time_record",
)
serializer_class = RecordSerializer
RE_VALIDATE_UTC = "(?<=utc)?((\+|\-)[0-1]{1}[0-9]{1})"
def utc_header(zone_time: str) -> str:
if zone_time and search(RE_VALIDATE_UTC, zone_time):
num_zone_time = search(
RE_VALIDATE_UTC,
zone_time,
).group()
if num_zone_time.startswith("-"):
hours = num_zone_time[:3].replace("-", "+")
elif num_zone_time.startswith("+"):
hours = num_zone_time[:3].replace("+", "-")
else:
hours = num_zone_time[:2]
if hours[1] == "0":
hours = hours.replace("0", "")
else:
hours = "0"
return hours
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.