将datetime.datetime对象序列化为JSON [英] Serialize datetime.datetime object as JSON

查看:135
本文介绍了将datetime.datetime对象序列化为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前正在使用python进行一个快速的小项目,并正在尝试将一个对象编码为JSON字符串.我已经做过几次了,除了现在没有任何问题.通常,我只执行以下操作.

Currently working on a quick little project in python and am attempting to encode an object into a JSON string. I've done this several times before without any problem except for now. Usually I just do the following.

def ClassToEncode :
    def __init__(self, arg1, arg2, ..., argn) :
        self.attr1 = arg1
        self.attr2 = arg2
        ...
        self.attrn = argn

     ...
     def toJSON(self) :
         return json.dumps(self, default=lambda o: o.__dict__)

但是问题是我的类属性之一是datetime.datetime对象,我被抛出以下错误

But the problem is that one of my class attributes is a datetime.datetime object and I am being thrown the following error

AttributeError: 'datetime.datetime' object has no attribute '__dict__'

任何想法或解决方案都可以启用将datetime属性包含到JSON输出中的功能?

Any thoughts or wraparounds that could enable the functionality of including the datetime attribute into the JSON output??

提前谢谢!

推荐答案

您可以使用 isoformat() 方法转换为ISO-8601格式的时间字符串,然后将其序列化为JSON就可以了.在另一端,在计算机上调用 datetime.datetime.strptime() 格式化的字符串,将其转换回datetime对象:

>>> from datetime import datetime as dt
>>> now = dt.now()
>>> now
datetime.datetime(2014, 9, 4, 3, 19, 44, 214096)
>>> isonow = now.isoformat()
>>> isonow
'2014-09-04T03:19:44.214096'
>>> format = "%Y-%m-%dT%H:%M:%S.%f"
>>> newtime = dt.strptime(isonow, format)
>>> newtime
datetime.datetime(2014, 9, 4, 3, 19, 44, 214096)

这篇关于将datetime.datetime对象序列化为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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