Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 891
nataila Avatar asked Dec 07 '15 08:12

nataila


People also ask

What is the format of datetime in Django?

And, because the format is dd/mm/yyyy, we must use a slash to separate the date, month and year.

What is Read_only true in Django?

Any 'read_only' fields that are incorrectly included in the serializer input will be ignored. Set this to True to ensure that the field is used when serializing a representation, but is not used when creating or updating an instance during deserialization.

How do I get the current date and time in Django?

First, open the views.py file of your Django application and import the datetime module. Next, use the datetime. now() method to get the current date and time value.

Why do we use Serializers in Django REST framework?

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.


2 Answers

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")
like image 56
xyres Avatar answered Sep 19 '22 06:09

xyres


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")
like image 26
Frederico Mateus Martins Avatar answered Sep 19 '22 06:09

Frederico Mateus Martins