2017-08-04 55 views
-1
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'",)列表寫入到文件j使用JSON解碼器編碼器

回答

1

第一件事:你想strftime()這裏沒有strptime()strptime()是用於解析的時間字符串到一個datetime.datetime對象)。

第二點:strftime()datetime.datetimedatetime.datedatetime.time對象的方法,所以正確的呼叫是

obj = obj.strftime(your_format_string_here)