1. 程式人生 > >Python 時間序列化方法

Python 時間序列化方法

import datetime
import json
from datetime import date

class DateTimeEncoder(json.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() d1 = date.today() print json.dumps(d, cls=DateTimeEncoder) print json.dumps(d1,cls=DateTimeEncoder)
解決以下問題:
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: datetime.datetime(2017, 2, 28, 18, 22, 9, 955000) is not JSON serializable