保留序列化程序中的本地时区

时间:2018-02-09 21:29:26

标签: django django-rest-framework

我有一个Django Rest Framework Serializer:

class LocalTZDateTimeField(serializers.DateTimeField):
    def __init__(self, *args, **kwargs):
        local_timezone = pytz.timezone(getattr(settings, 'LOCAL_TIMEZONE', None))
        kwargs['default_timezone'] = local_timezone
        super(LocalTZDateTimeField, self).__init__(*args, **kwargs)

显示如下日期:

"create_dt": "2016-01-04T09:06:17.344952-05:00" # Eastern time, as desired

我不想显示小数秒,因此文档建议指定日期时间格式,我做了:

'DATETIME_FORMAT': "%Y-%m-%dT%H:%M:%S%Z%z",

其中主要是,但现在日期转换为UTC "create_dt": "2016-01-04T14:06:17UTC+0000",

我无法找到任何可以让我在东方展示它们的东西。 (打开一个更好的解决方案来抑制小数秒,如果我不在标记处)

编辑:

为了澄清,目标是将现在的时间戳保持在东部,就像现在一样,但没有显示小数秒:

"2016-01-04T09:06:17-05:00"

我正在研究to_representation方法:

def to_representation(self, instance):
    representation = super(LocalTZDateTimeField, self).to_representation(instance)
    return representation

在中间设置pdb确认即使没有在设置中设置日期时间格式,representation也是我想要的 - 没有小数秒,正确的时区。但是,显示的内容仍然不正确:如果我不包含日期时间格式,则使用小数设置;错误的时区,如果我这样做。不知道该在哪里设置。

3 个答案:

答案 0 :(得分:1)

to representation方法是要走的路!

def to_representation(self, instance):
    format = "%Y-%m-%dT%H:%M:%S%Z%z"
    local_timezone = pytz.timezone(getattr(settings, 'America/New_York', None))
    representation = instance.astimezone(local_timezone).strftime(format)
    return representation

答案 1 :(得分:1)

我认为,this link对你有用。引自Django Rest Framework文档:

signature: DateTimeField(format=api_settings.DATETIME_FORMAT,
 input_formats=None)
  

format - 表示输出格式的字符串。如果没有指定,   此默认值与 DATETIME_FORMAT 设置键的值相同,   除非设定,否则为'iso-8601'。设置为格式字符串   表示应强制转换to_representation返回值   字符串输出。格式字符串如下所述。设置此值   to None表示应返回Python datetime对象   to_representation。在这种情况下,日期时间编码将是   由渲染器决定。

关于输入格式的有用部分:

  

input_formats - 字符串列表   表示可用于解析日期的输入格式。如果   未指定,将使用 DATETIME_INPUT_FORMATS 设置   默认为['iso-8601']。

答案 2 :(得分:0)

这对我有用:

from django.utils import timezone

def to_representation(self, instance):
    representation = instance.astimezone(timezone.get_default_timezone()).isoformat()
    return representation