2

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!

2

1 Answer 1

7

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'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.