[Solved]-How to get django queryset results with formatted datetime field

4👍

Got the solution.

data = list(Model.objects.extra(select={'date':"to_char(<DATABASENAME>_<TableName>.created_at, 'YYYY-MM-DD hh:mi AM')"}).values_list('date', flat='true')

It’s not just tablename.attribute, it should be dbname_tablename.attribute when we have multiple databases(ambiguous)

which will result list of created_at datetime values trimmed to ‘YYYY-MM-DD HH:MM’ format.

18👍

Solved it via @Yannics answer at: https://stackoverflow.com/a/60924664/5804947

This also avoids using extra which should be “a last resort” due to Django docs.

from django.db.models import F, Func, Value, CharField

qs.annotate(
  formatted_date=Func(
    F('created_at'),
    Value('DD-MM-YYYY HH:MM:SS'),
    function='to_char',
    output_field=CharField()
  )
)
👤Henhuy

1👍

I don’t think values() function would anything related to formatting datetime result. But why does that bother you? Can’t you convert them to proper format when you try to display them? If you try to render them in the template, django has template filter date for formatting your datetime value: https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#date

Leave a comment