Skip to content

Instantly share code, notes, and snippets.

@mylamour
Created February 6, 2017 03:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mylamour/f4cfd568f96175cd5c64afad7621f161 to your computer and use it in GitHub Desktop.
Save mylamour/f4cfd568f96175cd5c64afad7621f161 to your computer and use it in GitHub Desktop.
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