change Datetime format django rest framework

To provide more granular option, you can use SerializerMethodField:

class User (models.Model):
    user_id = models.AutoField(primary_key=True)
    user_name = models.CharField(max_length=150)
    created_at = models.SerializerMethodField()
    
    def get_created_at(self, obj):
        return obj.created_at.strftime("%Y-%m-%d %H:%M:%S")

And this format will only apply to this specific serializer attribute.

You can use this to any of your field with the format get_<field_name>. You can find more information in the documentation.


You can override to_representation method in a model serializer which required different date output:

class UserSerializer(serializers.ModelSerializer):
    ...
    def to_representation(self, instance):
        representation = super(UserSerializer, self).to_representation(instance)
        representation['created_at'] = instance.created_at.strftime(<your format string>)
        return representation

Or you can write custom field and use it instead of default.

class UserSerializer(serializers.ModelSerializer):
    created_at = serializers.DateTimeField(format='%Y')
    # add read_only=True to the field in case if date created automatically
    ...