Django datetime format different from DRF serializer datetime format

Viewed 7075

I am trying to understand why this is happening. I have a Django DateTime field and Django Rest Framework serializer that uses the field.

I am trying to compare the dates for both of them and get the following results from JSON endpoint and model result:

DRF: 2018-12-21T19:17:59.353368Z
Model field: 2018-12-21T19:17:59.353368+00:00

Is there a way to make them similar? So, either to make both of them be "Z" or "+00:00."

3 Answers

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.py

REST_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 serializers

class 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 Torkaman Ahmadi's answer)

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

from rest_framework import serializers

class YourSerializer(serializers.ModelSerializer):
    your_datetime_field = serializers.DateTimeField(format="%Y-%m-%dT%H:%M:%S")

    class Meta:
        model = YourModel
        fields = '__all__'
Related