溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

python2.7 json 轉(zhuǎn)換日期的處理的示例

發(fā)布時間:2020-10-08 12:01:13 來源:腳本之家 閱讀:123 作者:輕舞肥羊 欄目:開發(fā)技術(shù)

python2.7中 集成了json的處理(simplejson),但在實際應(yīng)用中,從mysql查詢出來的數(shù)據(jù),通常有日期格式,這時候,會報一個錯:

TypeError: datetime.datetime(2007, 7, 23, 12, 24, 25) is not JSON serializable

說明日期轉(zhuǎn)換出問題,后來再網(wǎng)上找到了解決辦法。

import json
from datetime import date, datetime


def __default(obj):
  if isinstance(obj, datetime):
    return obj.strftime('%Y-%m-%dT%H:%M:%S')
  elif isinstance(obj, date):
    return obj.strftime('%Y-%m-%d')
  else:
    raise TypeError('%r is not JSON serializable' % obj)

print json.dumps({
    'd': datetime.now(), 
    'today': date.today(), 
    'x': 111
  }, default=__default)

采用類似的方式,在得到mysql數(shù)據(jù)集后,需要序列化時,用如下方式就可以了。 

conn=self.getConnection();
cursor=conn.cursor();
cursor.execute(sqlText,params);
result=cursor.fetchall()
jsonstr=json.dumps(myresult,default=__default)
print jsonstr

關(guān)鍵點在于覆蓋了default 方法。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI