Reputation: 2025
I have a model that has a few DateTimeFields and TimeFields, and I am serializing them to JSON using:
json.dumps({'items': list(items.values('id','date_time','time'))},cls=DjangoJSONEncoder)
But the items list shows the date_time field as date_time": "2013-12-25T17:00:00".
How do I impose my own formatting for date_time or any DateTimeField/TimeField/DateField that gets JSON serialized?
Thanks
Upvotes: 0
Views: 2920
Reputation: 3631
You can write your own json encoder, look at the DjangoJSONEncoder. Instead of isoformat
you can use strftime
.
Upvotes: 1
Reputation: 12092
You could pre-process the fields in items
that need your own formatting using strftime. May be something like:
now = datetime.now()
desired_format = '%Y-%m-%dT%H-%M'
item['date_time']= now.strftime(desired_format)
Upvotes: 2