[Django]-How to format time in django-rest-framework's serializer?

42👍

The usual Python datetime format will work:

# for DateField
date = serializers.DateField(format="%Y-%m-%d")

# for DateTimeField
time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S")
👤xyres

12👍

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")

Leave a comment