Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
130 views
in Technique[技术] by (71.8m points)

javascript - Python和JavaScript之间的JSON日期时间(JSON datetime between Python and JavaScript)

I want to send a datetime.datetime object in serialized form from Python using JSON and de-serialize in JavaScript using JSON.(我想使用JSON从Python发送序列化形式的datetime.datetime对象,并使用JSON在JavaScript中反序列化。)

What is the best way to do this?(做这个的最好方式是什么?)   ask by translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can add the 'default' parameter to json.dumps to handle this:(您可以将'default'参数添加到json.dumps来处理:)

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"' Which is ISO 8601 format.(这是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(更新:还处理日期)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...