Python和JavaScript之间的JSON日期时间 [英] JSON datetime between Python and JavaScript
本文介绍了Python和JavaScript之间的JSON日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用 JSON 和de从Python发送序列化形式的datetime.datetime对象使用JSON在JavaScript中进行序列化。执行此操作的最佳方法是什么?
I want to send a datetime.datetime object in serialized form from Python using JSON and de-serialize in JavaScript using JSON. What is the best way to do this?
推荐答案
您可以将default参数添加到json.dumps来处理此问题:
You can add the 'default' parameter to json.dumps to handle this:
date_handler = lambda obj: (
obj.isoformat()
if isinstance(obj, (datetime.datetime, datetime.date))
else None
)
json.dumps(datetime.datetime.now(), default=date_handler)
'"2010-04-20T20:08:21.634121"'
ISO 8601 格式。
更全面的默认处理函数:
A more comprehensive default handler function:
def handler(obj):
if hasattr(obj, 'isoformat'):
return obj.isoformat()
elif isinstance(obj, ...):
return ...
else:
raise TypeError, 'Object of type %s with value of %s is not JSON serializable' % (type(obj), repr(obj))
更新:添加了类型和值的输出。
更新:还处理日期
Update: Added output of type as well as value.
Update: Also handle date
这篇关于Python和JavaScript之间的JSON日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文