Below the Radar
Below the Radar

Reputation: 7635

Django - change datetime field output format within values() method

I want to create a list of dict of a queryset where instances have a datetime fields in it. Then, I want to serialize it and send it in JSON.

I am using this code:

from django.core.serializers.json import DjangoJSONEncoder

objectList = Layers.objects.filter(geom_type="Polygon")
values = objectList.values('id', 'name', 'geom_type', 'date_created')
data = list(values)  # becomes list of dictionaries
jsonData = json.dumps(data, cls=DjangoJSONEncoder)
return HttpResponse(jsonData, content_type="application/json")

this is working good but I wonder if it's possible to choose the datetime field format to be yyyy-mm-dd-hh-mm-ss instead of 2014-12-09T16:05:12.132Z

Upvotes: 0

Views: 471

Answers (2)

jcfollower
jcfollower

Reputation: 3158

How about something like this ...

data = [[x.id, x.name, x.geom_type, x.date_created.strftime("%Y-%m-%d-%H-%M-%S")] 
        for x in objectList]

Or, if you are using the DATETIME_FORMAT setting, you can do

data = [[x.id, x.name, x.geom_type, '%s' % x.date_created] 
        for x in objectList]

Upvotes: 1

jcfollower
jcfollower

Reputation: 3158

Have you tried using a DATETIME_FORMAT setting?
https://docs.djangoproject.com/en/dev/ref/settings/

DATETIME_FORMAT = "Y-m-d-h-i-s"

Upvotes: 1

Related Questions