Created
February 6, 2017 03:07
-
-
Save mylamour/f4cfd568f96175cd5c64afad7621f161 to your computer and use it in GitHub Desktop.
json序列化dataime, 参考https://l1nwatch.gitbooks.io/writing_solid_python_code_gitbook/content/%E7%AC%AC%204%20%E7%AB%A0%20%E5%BA%93/readme.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import datetime | |
from time import mktime | |
try: | |
import simplejson as json | |
except ImportError: | |
import json | |
class DateTimeEncoder(json.JSONEncoder): # 为 JSONEncoder 进行扩展 | |
def default(self, obj): | |
if isinstance(obj, datetime.datetime): | |
return obj.strftime("%Y-%m-%d %H:%M:%S") | |
elif isinstance(obj, date): | |
return obj.strftime("%Y-%m-%d") | |
return json.JSONEncoder.default(self, obj) | |
d = datetime.datetime.now() | |
print(json.dumps(d, cls=DateTimeEncoder)) # 使用 cls 指定编码器的名称 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment