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'",)
答案 0 :(得分:1)
第一件事:您希望此处strftime()
而不是strptime()
(strptime()
用于将日期时间字符串解析为datetime.datetime对象。)
第二点:strftime()
是datetime.datetime
,datetime.date
和datetime.time
个对象的方法,因此正确的调用是
obj = obj.strftime(your_format_string_here)