Wei
Wei

Reputation: 201

Can I specify datetime format when using Django JSON serializer to serialize DatetimeField

It seems that it always serializes datetime field to iso format. My Django version is 1.6.5. My expected format is something like "2014-08-08 16:00:00". However, the output is always like "2014-08-08T16:00:00", no matter how I change the datetime format in settings. It seems that that setting cannot control the format for serialization. Do I have any way to change the format?

Upvotes: 0

Views: 5618

Answers (1)

ruddra
ruddra

Reputation: 51978

Instead of:

datetime.datetime.now().isoformat()

you have to use:

datetime.datetime.now().isoformat(' ')

Details here: https://docs.python.org/2/library/datetime.html#datetime.datetime.isoformat

EDIT

When you serialize the querystring using DjangoJSONEncoder, it parses datetime in isoformat(), so you need to override it.

import datetime
from django.core.serializers.json import DjangoJSONEncoder
import decimal
from django.utils.timezone import is_aware

class DjangoOverRideJSONEncoder(DjangoJSONEncoder):
    """
    JSONEncoder subclass that knows how to encode date/time and decimal types.
    """
    def default(self, o):
        # See "Date Time String Format" in the ECMA-262 specification.
        if isinstance(o, datetime.datetime):
            r = o.isoformat(' ')
            if o.microsecond:
                r = r[:23] + r[26:]
            if r.endswith('+00:00'):
                r = r[:-6] + 'Z'
            return r
        elif isinstance(o, datetime.date):
            return o.isoformat(' ')
        elif isinstance(o, datetime.time):
            if is_aware(o):
                raise ValueError("JSON can't represent timezone-aware times.")
            r = o.isoformat(' ')
            if o.microsecond:
                r = r[:12]
            return r
        elif isinstance(o, decimal.Decimal):
            return str(o)
        else:
            return super(DjangoOverRideJSONEncoder, self).default(o)

Now you need to use like this:

>>data= json.dumps(list(Model.objects.all()), cls=DjangoOverRideJSONEncoder)
>>print data
 '[{"last_updated": "2014-07-09 15:26:06",  "date_created": "2014-07-09 15:26:06","id": 11}, {"last_updated": "2014-08-25 10:48:31.946", "date_created": "2014-08-25 10:47:59.656", "id": 49093}]'

Upvotes: 4

Related Questions