作者 主題: python的datetime格式資料如何轉為json可接受的資料呢  (閱讀 8454 次)

0 會員 與 1 訪客 正在閱讀本文。

Quota

  • 活潑的大學生
  • ***
  • 文章數: 352
    • 檢視個人資料
    • http://home.kimo.com.tw/jiannrongkimo/
我從sqlite3讀取資料,想在python3.4內轉為json
可是這資料裡有dateime格式資料..執行時出現
AttributeError: 'tuple' object has no attribute 'date1'

我在網路上也試著做各種處理,但仍無法解決問題,所以想請問前輩,我的語法哪裡有錯?

我的程式語法如下

import sqlite3
import sys
import json
import time
db = sqlite3.connect('flag.db')
cursor = db.cursor()
cursor.execute('''SELECT datetime as date1,f1,f2 FROM data ORDER BY datetime desc limit 10''')
user1 = cursor.fetchone() #retrieve the first row
all_rows = cursor.fetchall()
for row in all_rows:
    #py_date = row.date1.datetime(row.date1)
    d['date'] = row.date1.strftime("%Y-%m-%d %H:%M:%S")
    #tm = row.datetime.strptime("%Y-%m-%d %H:%M:%S")
    t = (d['date'],row.f1,row.f2)
    rowarray_list.append(t)
j = json.dumps(rowarray_list)
print(j)

我的資料,共計十筆,我寫了一隻程式如下
import sqlite3
import sys
db = sqlite3.connect('flag.db')
cursor = db.cursor()
cursor.execute('''SELECT datetime,f1,f2 FROM data ORDER BY datetime desc limit 10''')
user1 = cursor.fetchone() #retrieve the first row
all_rows = cursor.fetchall()
for row in all_rows:
    # row[0] returns the first column in the query (name), row[1] returns email column.
    print('{0} : {1}, {2}'.format(row[0], row[1], row[2]))
   
可顯示如下
2014-05-03 10:57:34 : 25.4, 60.0
2014-05-03 10:57:24 : 25.5, 60.0
2014-05-03 10:57:14 : 25.4, 60.0
2014-05-03 10:57:04 : 25.4, 60.0
2014-05-03 10:56:54 : 25.4, 60.0
2014-05-03 10:56:44 : 25.3, 60.0
2014-05-03 10:56:34 : 25.3, 60.0
2014-05-03 10:56:23 : 25.3, 60.0
2014-05-03 10:56:13 : 25.3, 60.0

目前卡在第一個欄位資料無法轉為json資料
煩請各位協助
謝謝

darkranger

  • 榮譽學長
  • 俺是博士!
  • *****
  • 文章數: 1384
    • 檢視個人資料
    • https://darkranger.no-ip.org
沒處理過類似需求
但我還真的完全看不懂這段程式碼
1.
有沒有查過 row 出來是什麼資料型態?
2.
datetime()、strftime()、strptime() 等函式無中生有,怎麼來的?

Quota

  • 活潑的大學生
  • ***
  • 文章數: 352
    • 檢視個人資料
    • http://home.kimo.com.tw/jiannrongkimo/
沒處理過類似需求
但我還真的完全看不懂這段程式碼
1.
有沒有查過 row 出來是什麼資料型態?
2.
datetime()、strftime()、strptime() 等函式無中生有,怎麼來的?

資料庫內的資料 這三個欄位分別為 datetime float float
請問要如何檢查row出來的資料型態?
sqlite不分型態  不過資料一開始是在mysql 所以格式是這樣...
還是sqlite讀取出來是字串 可是
python執行後的錯誤訊息是
AttributeError: 'tuple' object has no attribute 'date1'
所以資料不是當字串使用?

另外請教 我想我是不太會查資料
python網站上關於 strftime() 
   https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
我看不出來他是屬於哪一個需要import項目
可否再多一些提醒?
畢竟現在資料可以撈出了 就卡在日期時間的轉換..
或者麻煩前輩多一點提示..我可以試著解決問題..
最後一哩路了..謝謝!
« 上次編輯: 2014-11-21 16:21 由 Quota »

darkranger

  • 榮譽學長
  • 俺是博士!
  • *****
  • 文章數: 1384
    • 檢視個人資料
    • https://darkranger.no-ip.org
SQL 的 datetime 跟 Python 的 datetime 是兩回事
前者是資料型態,後者是一種可載入(import)的模組

出來的 row 是 tuple 型態,tuple 是一種陣列,接下來就是用陣列的邏輯處理
如果陣列的內容是字串,就接著用字串的邏輯處理成想要的結果




Quota

  • 活潑的大學生
  • ***
  • 文章數: 352
    • 檢視個人資料
    • http://home.kimo.com.tw/jiannrongkimo/
不好意思 經由前輩指點  給我些提示  我發現我被誤導?
修改後可以跑 修改後的語法如下
import sqlite3
import sys
import json
import time
db = sqlite3.connect('flag.db')
cursor = db.cursor()
cursor.execute('''SELECT datetime as date1,f1,f2 FROM data ORDER BY datetime desc limit 10''')
user1 = cursor.fetchone() #retrieve the first row
all_rows = cursor.fetchall()
rowarray_list = []
for row in all_rows:
    #py_date = row.date1.datetime(row.date1)
    #d['date'] = row[0].strftime("%Y-%m-%d %H:%M:%S")
    #tm = row.datetime.strptime("%Y-%m-%d %H:%M:%S")
    #t = (d['date'],row[1],row[2])
    t = (row[0]+','+str(row[1])+','+str(row[2]))
    rowarray_list.append(t)
j = json.dumps(rowarray_list)
print(j)

Quota

  • 活潑的大學生
  • ***
  • 文章數: 352
    • 檢視個人資料
    • http://home.kimo.com.tw/jiannrongkimo/
不行
輸出的資料json仍不能接收
我再次進行轉換 語法修改如下
import sqlite3
import sys
import json
import datetime
#datetime.datetime.strptime('24052010', '%d%m%Y').date()
##tm = row.datetime.strptime("%Y-%m-%d %H:%M:%S")

db = sqlite3.connect('flag.db')
cursor = db.cursor()
cursor.execute('SELECT datetime as date1,f1,f2 FROM data ORDER BY datetime asc limit 10')
user1 = cursor.fetchone() #retrieve the first row
all_rows = cursor.fetchall()
rowarray_list = []
t = ('datetime','f1','f2')
rowarray_list.append(t)
for row in all_rows:
    print('{0} : {1}, {2}'.format(row[0], row[1], row[2]))   
    t = (datetime.datetime.strptime(row[0], '%Y-%m-%d %H:%M:%S').date(),row[1],row[2])
    rowarray_list.append(t)
j = json.dumps(rowarray_list)

輸出畫面如下
2011-02-08 04:36:15 : 31.6, NULL
2011-02-09 01:37:05 : 30.6, 81.0
2011-02-09 19:02:09 : 22.1, 77.0
2011-02-10 18:21:47 : 21.5, 80.0
2011-02-11 08:42:04 : 23.2, 85.0
2011-02-11 18:32:01 : 28.1, 80.0
2011-02-12 09:42:05 : 31.6, 82.0
2011-02-12 17:42:05 : 25.9, 85.0
2011-02-12 21:42:05 : 22.9, 80.0
Traceback (most recent call last):
  File "flag3.py", line 20, in <module>
    j = json.dumps(rowarray_list)
  File "c:\Python34\lib\json\__init__.py", line 230, in dumps
    return _default_encoder.encode(obj)
  File "c:\Python34\lib\json\encoder.py", line 192, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "c:\Python34\lib\json\encoder.py", line 250, in iterencode
    return _iterencode(o, 0)
  File "c:\Python34\lib\json\encoder.py", line 173, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: datetime.date(2011, 2, 8) is not JSON serializable



Yamaka

  • 俺是博士!
  • *****
  • 文章數: 4913
    • 檢視個人資料
    • http://www.ecmagic.com
不行
輸出的資料json仍不能接收
我再次進行轉換 語法修改如下
import sqlite3
import sys
import json
import datetime
#datetime.datetime.strptime('24052010', '%d%m%Y').date()
##tm = row.datetime.strptime("%Y-%m-%d %H:%M:%S")

db = sqlite3.connect('flag.db')
cursor = db.cursor()
cursor.execute('SELECT datetime as date1,f1,f2 FROM data ORDER BY datetime asc limit 10')
user1 = cursor.fetchone() #retrieve the first row
all_rows = cursor.fetchall()
rowarray_list = []
t = ('datetime','f1','f2')
rowarray_list.append(t)
for row in all_rows:
    print('{0} : {1}, {2}'.format(row[0], row[1], row[2]))   
    t = (datetime.datetime.strptime(row[0], '%Y-%m-%d %H:%M:%S').date(),row[1],row[2])
    rowarray_list.append(t)
j = json.dumps(rowarray_list)

輸出畫面如下
2011-02-08 04:36:15 : 31.6, NULL
2011-02-09 01:37:05 : 30.6, 81.0
2011-02-09 19:02:09 : 22.1, 77.0
2011-02-10 18:21:47 : 21.5, 80.0
2011-02-11 08:42:04 : 23.2, 85.0
2011-02-11 18:32:01 : 28.1, 80.0
2011-02-12 09:42:05 : 31.6, 82.0
2011-02-12 17:42:05 : 25.9, 85.0
2011-02-12 21:42:05 : 22.9, 80.0
Traceback (most recent call last):
  File "flag3.py", line 20, in <module>
    j = json.dumps(rowarray_list)
  File "c:\Python34\lib\json\__init__.py", line 230, in dumps
    return _default_encoder.encode(obj)
  File "c:\Python34\lib\json\encoder.py", line 192, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "c:\Python34\lib\json\encoder.py", line 250, in iterencode
    return _iterencode(o, 0)
  File "c:\Python34\lib\json\encoder.py", line 173, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: datetime.date(2011, 2, 8) is not JSON serializable

看錯誤訊息是資料格式 json 不接受
因為 datetime.date 實際上是一個 class

看不懂樓主這一串的目的是什麼?
datetime.datetime.strptime(row[0], '%Y-%m-%d %H:%M:%S').date()

如果只是想得到 “2011, 2, 8” 類似這樣的日期字串
上面那一串改成這樣試試吧

row[0].split(' ')[0].replace('-', ',')

代碼: [選擇]
>>> row[0] = '2011-02-09 01:37:05'
>>> json.dumps((row[0].split(' ')[0].replace('-', ','), 30.6, 81.0))
'["2011,02,09", 30.6, 81.0]'

ps:
第1筆資料的 NULL 也會有問題
建議改資料表欄位預設為 0 就不會出現 NULL

Quota

  • 活潑的大學生
  • ***
  • 文章數: 352
    • 檢視個人資料
    • http://home.kimo.com.tw/jiannrongkimo/
感謝
問題解決了