5

My Django install uses a PostgreSQL backend.

I am doing the following in a Django view:

completedItems = Completed.objects.filter(user_id=1)
return HttpResponse(completedItems.values('item_id','item_name','event_datetime','item_id__item_name'))

For the date timefield, this returns:

'event_datetime': datetime.datetime(2014, 6, 4, 0, 49, 38, tzinfo=<UTC>)

I am trying to serialize the return using json.dumps, and this formatting is giving me grief. What is the best way to reformat the datetime return from the query so I can serialize it properly?

I tried to use:

datetime.strptime('event_datetime',"datetime.datetime(%Y, %m, %d, %H, %M, %S, tzinfo=<%Z>)")

but it complains that the date does not match the format string.

2
  • 1
    I don't understand what you are trying to do. strptime is for converting a string to a datetime, but you seem to have a datetime already. Commented Jun 14, 2014 at 20:25
  • Ahh, sorry. I left out an important detail. I'm trying to convert the datetime into a string that I can serialize and pass to another app in JSON (this Django app is essentially serving as a REST server). I'm looking for a good way to get a seralizable string from a datetime. Commented Jun 15, 2014 at 13:32

2 Answers 2

8

For use "to_char" function PostgreSQL in some queryset possibly via annotate with Func, (from Django 1.8)

rows = some_queryset.annotate(str_date=Func(F('date'), Value('DD.MM.YYYY'), function='to_char'))

then each item in rows has 'str_date' as string date in format 'DD.MM.YYYY'

  • from django.db.models import Func, F, Value
  • 'date' in F('date') is field of Model with datetime data
Sign up to request clarification or add additional context in comments.

Comments

0

I ended up using .extra to inject PostgreSQL "to_char" to re-format this. This is the solution suggested by PKKid here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.