【问题标题】:How to convert Python datetime object to specific timezone in Django Rest Framework?如何将 Python 日期时间对象转换为 Django Rest Framework 中的特定时区?
【发布时间】:2019-07-16 15:49:04
【问题描述】:

我正在开发一个使用Djangodjango-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


    【解决方案1】:

    您需要在您的settings.py 中添加set TIME_ZONE。只需将'timestamp' 放入fields 列表中,它就可以开箱即用。

    为了明确,你也可以写

    timestamp = serializers.DateTimeField(format='iso-8601')
    

    请注意,我假设您的所有回复都使用一个主要时区。如果您需要返回用户发送的时区时间,请参阅this answer

    【讨论】:

      猜你喜欢
      • 2021-06-29
      • 2014-10-28
      • 1970-01-01
      • 2013-02-16
      • 2011-12-02
      • 1970-01-01
      • 2015-08-18
      • 2013-11-10
      • 2010-12-06
      相关资源
      最近更新 更多