Chris Dutrow
Chris Dutrow

Reputation: 50362

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 exception:

TypeError: datetime.datetime(2012, 6, 5, 17, 49, 35, 672115) is not JSON serializable

Using Python 2.7, is there a way to tell the json serializer: "When you see a datetime, don't be annoying and throw an exception, just serialize using: property.strftime('%Y-%m-%d %I:%M%p')"

Thanks!

Upvotes: 2

Views: 7075

Answers (1)

Pavel Repin
Pavel Repin

Reputation: 30953

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()

def serialize_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'

Upvotes: 7

Related Questions