Home > Backend Development > Python Tutorial > 让python json encode datetime类型

让python json encode datetime类型

WBOY
Release: 2016-06-06 11:27:39
Original
1349 people have browsed it

实现代码如下:

代码如下:


import json
from datetime import date, datetime


def __default(obj):
if isinstance(obj, datetime):
return obj.strftime('%Y-%m-%dT%H:%M:%S')
elif isinstance(obj, date):
return obj.strftime('%Y-%m-%d')
else:
raise TypeError('%r is not JSON serializable' % obj)

print json.dumps({'d': datetime.now(), 'today': date.today(), 'x': 111},
default=__default)

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template