Search code examples
pythondjangodatetimeserializationpython-datetime

Django model DateTimeField set auto_now_add format or modify the serializer


I have this field in my model:

createdTime = models.DateTimeField(_('Creation date'), help_text=_('Date of the creation'),
                                   auto_now_add=True, blank=True)

And it is saved with this format:

2016-05-18T15:37:36.993048Z

So I would like to convert it to this format DATE_INPUT_FORMATS = ('%d-%m-%Y %H:%M:S') but I dont know where to do it.

I have a simple serializer class, could I override it to modify the format? or maybe create a get_date() model method?

class ObjectSerializer(serializers.ModelSerializer):
    """
    Serializer for object.
    """
    class Meta:
        model = Object

My settings:

DATETIME_FORMAT = '%d-%m-%Y %H:%M:%S'

USE_I18N = True

USE_L10N = False

USE_TZ = False

Solution

  • Set DATETIME_FORMAT in your settings.py as specified here.

    The default formatting to use for displaying datetime fields in any part of the system. Note that if USE_L10N is set to True, then the locale-dictated format has higher precedence and will be applied instead

    The date part of your settings.py should afterwards look like so:

    DATETIME_FORMAT = '%d-%m-%Y %H:%M:%S' 
    USE_L10N = False
    USE_TZ = False # if you plan to disable timezone support
    

    Alternatively, you can manually change formats after retrieval by doing:

    import datetime
    
    datetime_str = '2016-05-18T15:37:36.993048Z'
    old_format = '%Y-%m-%dT%H:%M:%S.%fZ'
    new_format = '%d-%m-%Y %H:%M:%S'
    
    new_datetime_str = datetime.datetime.strptime(datetime_str, old_format).strftime(new_format)
    print(new_datetime_str)
    #'18-05-2016 15:37:36'
    

    This conversion can be added to your serializer or model as your proposed get_date() method