字典列表写入jusing json解码器编码器的文件

时间:2017-08-04 11:10:02

标签: python python-3.x

import datetime

class MyEncoder1(json.JSONEncoder):

    def default(self, obj):

        if isinstance(obj,datetime.date):

            obj= datetime.strptime(obj,"%Y-%m-%d ")

        elif isinstance(obj, datetime.datetime):

            obj= datetime.strptime(obj,"%Y-%m-%d %H:%M:%S.%f")

        elif isinstance(obj, datetime.time):

            obj = datetime.time.strftime(obj,"%H:%M:%S")

        elif isinstance(obj, Decimal):

            obj = float(obj)
        else:
            obj = super(MyEncoder1, self).default(obj)
        return obj

json_array = dumps(data,cls=MyEncoder1)

with open(filename,"a") as fobj:

    for index in range(0,len(json_array)):
        fobj.write(json_array[index])
    fobj.close()

我收到错误AttributeError("module 'datetime' has no attribute 'strptime'",)

1 个答案:

答案 0 :(得分:1)

第一件事:您希望此处strftime()而不是strptime()strptime()用于将日期时间字符串解析为datetime.datetime对象。)

第二点:strftime()datetime.datetimedatetime.datedatetime.time个对象的方法,因此正确的调用是

obj = obj.strftime(your_format_string_here)