简体   繁体   中英

Change Date Time Format in Django REST Object

I've been trying to tackle this problem for quite a while now. please help if possible...

I have a REST framework response where one of the datetime values is in UTC format. I want to change this format into a more friendly format.

rest framework output:

{ 
    "data": [
        {
            "id": "1",
            "start_time": "2017-12-28T12:56:55-08:00",
        },
        {
            "id": "2",
            "start_time": "2017-12-28T12:14:10-08:00",
        },
        {
            "id": "3",
            "start_time": "2017-12-28T09:37:35-08:00",
        },        
    ]
}

views: (my code to change the start_time format in the display)

serializer = ChangeLogSerializer(changelog['items'], many=True)
for log in serializer.data:
    serializer.data[log]['start_time'] = log['start_time'].strftime('%Y-%m-%d %T')  

serializers.py

class ChangeLogSerializer(serializers.ModelSerializer):
    """Serializer to map the Model instance into JSON format."""

    class Meta:
        """Meta class to map serializer's fields with the model fields."""
        start_time = serializers.DateField(format="%y-%m-%d %H:%M:%S")
        model = ChangeLog

        fields = ('id', 'sku', 'serial_num', 'mac', 'sw_ver',
                  'state', 'outcome', 'logfile', 'process',
                  'cm', 'site', 'port_num', 'term_srvr',
                  'start_time', 'end_time')
        read_only_fields = ('start_time', 'end_time')

Observations:

  • serializer.data[log] doesn't appear to be correct way to update this item
  • gives error message: File "/root/venv/dashbaord/lib/python3.4/site-packages/rest_framework/utils/encoders.py", line 68, in default return super(JSONEncoder, self).default(obj)
  • Tried in my serializers.py file to adjust the format: start_time = serializers.DateField(format="%y-%m-%d %H:%M:%S"), but it doesn't do anything

Found the answer, changed in settings.py file:

REST_FRAMEWORK = {
    'DATETIME_FORMAT': "%Y-%m-%d - %H:%M:%S",
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM