python - 如何从 Django Rest Framework 序列化程序返回不同时区的 DateTime

标签 python django datetime django-rest-framework timezone

在 Django Rest Framework 中使用任意时区返回某些 Django 模型的 DateTimeField 的 Pythonic 方法是什么?

目前,我的 View 返回 UTC 格式的日期时间,因为据我所知,Django 将时区感知的日期时间存储为 UTC 时区的日期时间。

型号:

class TimezoneMixin(models.Model):
    TIMEZONES = [(i, i) for i in country_timezones['ru']]

    timezone = models.CharField(choices=TIMEZONES, ...)

    class Meta:
        abstract = True

    def get_timezone(self):
        if self.timezone:
            return timezone(self.timezone)
        return get_current_timezone()


class Organization(TimezoneMixin, models.Model):
    ...

class Event(models.Model):
    organization = models.ForeignKey(Organization, ...)
    date_created = models.DateTimeField(auto_now_add=True, ...)
    ...

序列化器:

class EventSerializer(serializers.ModelSerializer):

    class Meta:
        model = Event
        fields = ('organization', 'date_created', ...)

在 ViewSet 中,我填充数据如下

organization_id = ...  # Some logic to get required organization_id

data = {
    'date_created': timezone.now(), # django.utils.timezone
    'organization': organization_id,
    ...
}

serializer = EventSerializer(data=data)
if serializer.is_valid():
    serializer.save()
    response_data = serializer.data.copy()
    # Some logic to rename one of the keys in response data
    ...
    return Response(response_data, ...)  # rest_framework.response.Response

即使我将 timezone.now() 替换为 timezone.now().astimezone(organization.get_timezone()) 我仍然会收到 UTC DateTime 响应.

我是否正确,从 response_data 解析 date_created 字符串,从中创建一个 DateTime 对象,转换为不同的时区并再次格式化为字符串不是一个好主意到底是 View ?还有哪些方法?

最佳答案

您需要localtime()获取当前时区的时间,因为无论 TIME_ZONE 的值如何,now() 始终返回 UTC 时间。

您可以将任意时区传递给本地时间:

localtime(timezone='SOMETHING')

关于python - 如何从 Django Rest Framework 序列化程序返回不同时区的 DateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53749712/

相关文章:

c# - 如何在 C# 中获取加拿大安大略省的当前日期时间值?

python - 使用函数指针作为 Python 的参数调用 Tcl 过程

python - python unittest 导入问题

Django 存储 s3 媒体网址为 https ://instead of http://

python - 如何在 Django 模型中动态设置类的属性?

php - 日期和时间差异与色差

php - 从 php 获取数据到 datetime-local

python - Hook Python 标准库模块

python - 使用 praw 从 reddit 获取前 10 名帖子

python - 使用 Django,我如何在单个查询中实现此目的?