Thursday, March 10, 2016

Re: Odd behaviour of DjangoJSONSerializer when serializing datetimes with/without microseconds

Hi Rob,

The fact DjangoJSONEncoder strips microseconds is definitely a bug that should
be reported:

> e.default(datetime.datetime(year=2016, month=1, day=1, hour=1, minute=1, second=1, microsecond=123456))
> '2016-01-01T01:01:01.123'

I think always including the microseconds could make sense but I'm not sure it's
worth it in regard to backward incompatiblity. Keep in mind that Django relies
on the `datetime.datetime.isoformat` stdlib method which does the stripping
internally:

> datetime.datetime(year=2016, month=1, day=1, hour=1, minute=1, second=1).isoformat()
> '2016-01-01T01:01:01'

Cheers,
Simon

> e.default(datetime.datetime(year=2016, month=1, day=1, hour=1, minute=1, second=1, microsecond=123456))
> '2016-01-01T01:01:01.123'

I think always including the microseconds could make sense but since it might have backward compatibility

Le jeudi 10 mars 2016 07:52:49 UTC-5, Robert Kirberich a écrit :
Hi,

I stumbled across this yesterday while trying to figure out why some of my tests would sometimes fail when serializing and deserializing datetimes to JSON.

DjangoJSONSerializer only includes the milliseconds in the encoded string if the original datetime has a non-zero microsecond value - this is fine when only dealing with the JSON in Javascript, but in python it requires two different cases when decoding.

To make things even more confusing, the milliseconds field can be included even if it's zero:

import datetime
from django.core.serializers.json import DjangoJSONEncoder
e
= DjangoJSONEncoder()

e
.default(datetime.datetime(year=2016, month=1, day=1, hour=1, minute=1, second=1, microsecond=1))
'2016-01-01T01:01:01.000'

e
.default(datetime.datetime(year=2016, month=1, day=1, hour=1, minute=1, second=1, microsecond=0))
'2016-01-01T01:01:01'



This seems like a bug to me (easily fixed by always including the milliseconds), but I wanted to check first if there's a reason for this behaviour, as that code has been there for ages. If this is a bug, I'll be happy to send a PR.


Cheers
Rob

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/2a9557eb-55aa-4a94-a578-58603956b4d9%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment