Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

How to serialize datetime.datetime not json?


Asked by Leon Benson on Dec 02, 2021 JSON



The original answer accommodated the way MongoDB "date" fields were represented as: If you want a generic Python solution for serializing datetime to json, check out @jjmontes' answer for a quick solution which requires no dependencies. Django provides a native DjangoJSONEncoder serializer that deals with this kind of properly.
Likewise,
JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation.
In this manner, JSON Dates are not dates – they are Strings. The problem with dates in JSON – and really JavaScript in general – is that JavaScript doesn’t have a date literal. You can represent strings, numbers, Booleans and even objects, arrays and RegEx expressions with language specific literals, but there’s no equivalent literal representation for dates.
Moreover,
class datetime. time. An idealized time, independent of any particular day, assuming that every day has exactly 24*60*60 seconds. (There is no notion of “leap seconds” here.) Attributes: hour, minute, second, microsecond , and tzinfo. class datetime. datetime. A combination of a date and a time.
Additionally,
Form data can be serialized by both jQuery and JavaScript but, the major difference between them is that, jQuery’s serialize () method returns form field values in top down sequence whereas, serialize JavaScript returns it in bottom up sequence.