获取Python JSON序列化日期时间 [英] Get Python JSON to serialize datetime

查看:465
本文介绍了获取Python JSON序列化日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一些我想使用JSON序列化的嵌套对象。问题是某些属性包含 datetime s。当我尝试序列化这些对象时,Python抛出一个异常:

 
TypeError:datetime.datetime(2012,6,5,17,49 ,35,672115)不是JSON可序列化

使用Python 2.7,有没有办法告诉json serializer:当你看到datetime,不要烦人,抛出异常,只是序列化使用: property.strftime('%Y-%m-%d%I:%M%p')



谢谢!

解决方案

一个帮助函数,将序列化 datetime 对象,并使用默认 kwarg json.dump 或json.dumps。



此外,您还需要考虑是否支持时区感知 datetime 对象。以及是否要在序列化期间保留时区,或者仅在序列化之前转换为UTC。



以下是一个示例,假设您要在序列化之前转换为UTC。它依赖于 python-dateutil 库:

  from dateutil.tz import tzutc 

UTC = tzutc()

def serialize_date(dt):

将日期/时间值序列化为ISO8601文本表示
调整(如果需要)到UTC时区

例如:
>>> serialize_date( datetime(2012,4,10,22,38,20,604391))
'2012-04-10T22:38:20.604391Z'

如果dt.tzinfo:
dt = dt.astimezone(UTC).replace(tzinfo = None)
返回dt.isoformat()+'Z'


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!

解决方案

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'

这篇关于获取Python JSON序列化日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆