【发布时间】:2019-07-16 15:49:04
【问题描述】:
我正在开发一个使用Django 和django-rest-framework 实现api 的现有代码库。当您发布这样的日期时间时:
2019-06-21T10:35:46+02:00
它以 UTC 格式存储为 2019-06-21 08:35:46+00(如预期的那样)。这是因为我有USE_TZ = True。
当我提供数据时,我还希望将其再次转换为本地化格式 (2019-06-21T10:35:46+02:00)。所以在this tip之后我是这样实现的:
class DateTimeFieldWihTZ(serializers.DateTimeField):
""" Class to make output of a DateTime Field timezone aware """
def to_representation(self, value):
value = timezone.localtime(value)
return super(DateTimeFieldWihTZ, self).to_representation(value)
class PeopleMeasurementSerializer(HALSerializer):
class Meta:
model = PeopleMeasurement
fields = [
'_links',
'id',
'timestamp',
'sensor',
'count'
]
timestamp = DateTimeFieldWihTZ(format='%Y-%m-%d %H:%M:%S')
但这是2019-06-21 08:35:46。我怎样才能再次将其用作2019-06-21T10:35:46+02:00?
【问题讨论】:
标签: python django datetime django-rest-framework timezone