how to format time in django-rest-framework's

2020-03-12 04:02发布

there is my serializer code:
serializer.py

class StartListSerializer(serializers.Serializer):
    id = serializer.CharField()
    time = serializers.DateField(fromat=None, input_formats=None) 

it will give me this:
'time': '2014-03-14T22:44:16.923000'
the input time format is datetime.datetime(2014, 3, 14, 22, 44, 37, 280000)
But I want to get time like this 2014-03-14 22:44:37
how can I change my serializer to get this time?

2条回答
\"骚年 ilove
2楼-- · 2020-03-12 04:54

The usual Python datetime format will work:

time = serializers.DateField(format="%Y-%m-%d %H:%M:%S")
查看更多
在下西门庆
3楼-- · 2020-03-12 04:57

After testing the accepted answer, I got the following error:

AssertionError: Expected a date, but got a datetime. Refusing to coerce, as this may mean losing timezone information. Use a custom read-only field and deal with timezone issues explicitly.

Using the serializer field as datetime solved the issue.

class StartListSerializer(serializers.Serializer):

    # ...
    time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S")
查看更多
登录 后发表回答