我有一个 Django Rest Framework 序列化器:
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"# 东部时间,根据需要
我不想显示秒的小数部分,因此文档建议指定日期时间格式,我这样做了:
'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 可以确认,即使没有在设置中设置日期时间格式,表示
也是我想要的——没有小数秒,正确的时区。但是,显示的内容仍然不正确:如果我不包含日期时间格式,则使用小数设置;如果我这样做的话,时区是错误的。不确定在哪里设置。
最佳答案
torepresentation
方法就是正确的选择!
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
关于django - 在序列化器中保留本地时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48714349/