[Django]-Django rest framework datetime field format

48๐Ÿ‘

โœ…

You can specify a format parameter to the ordered_date field having value as a string representing the output format.

ordered_date = serializers.DateTimeField(format="%Y-%m-%dT%H:%M:%S", required=False, read_only=True)

For example:

In [1]: from rest_framework import  serializers

In [2]: from datetime import datetime

In [3]: class XYZSerializer(serializers.Serializer): # define a serializer with a datetime field
   ...:     ordered_date = serializers.DateTimeField(format="%Y-%m-%dT%H:%M:%S")
   ...:    

In [4]: x = XYZSerializer(data={'ordered_date':datetime.now()})

In [5]: x.is_valid()
Out[5]: True

In [6]: x.data # contains the datetime field in the desired format
Out[6]: OrderedDict([('ordered_date', '2015-10-22T18:17:51')])
๐Ÿ‘คRahul Gupta

18๐Ÿ‘

Thanks to @Red-Tune-84โ€™s comment
I customize the format of all my datetimefields.

REST_FRAMEWORK = {
    'DATETIME_FORMAT': "%Y-%m-%d %H:%M:%S",
    ....
}
๐Ÿ‘คC.K.

Leave a comment