Django datetime format different from DRF serializer datetime format Django datetime format different from DRF serializer datetime format django django

Django datetime format different from DRF serializer datetime format


It's because django rest framework uses it's own datetime formating. To change that, in your settings.py file, there should exist a dict variable called REST_FRAMEWORK (if not create it) and add this:

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

Also check USE_TZ variable state too in your settings.py


I came here from google looking for a quick fix to get this (e.g. copy and paste). So, borrowing from @RezaTorkamanAhmadi's answer, for anyone looking to get a DRF serializer DateTimeField to have the format 2018-12-21T19:17:59.353368+00:00 (the same format as the default models.DateTimeField so that your serialized values match your model values -- the OP's question and mine too) you're looking for either:

# settings.pyREST_FRAMEWORK = {    ...    'DATETIME_FORMAT': "%Y-%m-%d %H:%M:%S.%f%z",     ...}

or if you just want it for a specific DateTimeField serializer field you're looking for

from rest_framework import serializersclass MySerializer(serializers.Serializer):    some_date = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S.%f%z")

Sources:

  1. https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior
  2. https://www.django-rest-framework.org/api-guide/fields/#datetimefield
  3. https://stackoverflow.com/a/53893377/10541855 (Reza TorkamanAhmadi's answer)


Apart from previous answer, also you can change DateTime format in your serializer.

from rest_framework import serializersclass YourSerializer(serializers.ModelSerializer):    your_datetime_field = serializers.DateTimeField(format="%Y-%m-%dT%H:%M:%S")    class Meta:        model = YourModel        fields = '__all__'