Skip to content Skip to sidebar Skip to footer

Get Python Json To Serialize Datetime

Have some nested objects that I'd like serialize using JSON. The problem is that some of the properties contain datetimes. When I try to serialize these pbjects, Python throws an e

Solution 1:

You'll want to define a helper function that will serialize datetime objects, and use default kwarg of json.dump or json.dumps. See the comments with links to the duplicate answers.

Also, you will want to consider whether to support or not to support timezone-aware datetime objects. And whether you want to preserve the timezone during the serialization or just convert to UTC prior to serialization.

Here's an example that assumes you want to convert to UTC before serialization. It relies upon python-dateutil library:

from dateutil.tz import tzutc

UTC = tzutc()

defserialize_date(dt):
    """
    Serialize a date/time value into an ISO8601 text representation
    adjusted (if needed) to UTC timezone.

    For instance:
    >>> serialize_date(datetime(2012, 4, 10, 22, 38, 20, 604391))
    '2012-04-10T22:38:20.604391Z'
    """if dt.tzinfo:
        dt = dt.astimezone(UTC).replace(tzinfo=None)
    return dt.isoformat() + 'Z'

Post a Comment for "Get Python Json To Serialize Datetime"