2012-11-11 88 views
1

我是Python 2.6的新手。我一直試圖獲取日期datetime值,它的格式爲yyyy-mm-dd hh:m:ss,在我的Python程序中。在檢查Python中的列類型時,我得到錯誤:'buffer' object has no attribute 'decode'。我想使用strptime()函數來拆分日期數據並使用它,但是我找不到如何將緩衝區轉換爲字符串。以下是我的代碼(也可用here)樣本:Python:將緩衝區類型的SQLITE列轉換爲字符串

conn = sqlite3.connect("mrp.db.db", detect_types=sqlite3.PARSE_DECLTYPES) 
cursor = conn.cursor() 
qryT = """ 
    SELECT dateDefinitionTest FROM t 
    WHERE IDproject = 4 AND IDstatus = 5 
    ORDER BY priority, setDate DESC 
""" 
rec = (4,4) 
cursor.execute(qryT,rec) 
resultsetTasks = cursor.fetchall() 
cursor.close() # closing the resultset 
for item in resultsetTasks: 
    taskDetails = {} 
    _f = item[10].decode("utf-8") 

我得到的例外是:

'buffer' object has no attribute 'decode' 
+0

請顯示您的代碼和確切的錯誤。 –

+0

http://pastie.org/5360165 ** dateDefinitionTest **是sqlite3字段的_datetime_ – Volatil3

+0

錯誤我得到:**'緩衝區'對象沒有屬性'解碼'** – Volatil3

回答

2

我不完全相信你的問題可能是什麼。以下是你想達到什麼樣的工作的例子,它希望能幫助您:

#!/usr/bin/env python 

import datetime 
import sqlite3 

conn = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES) 
cursor = conn.cursor() 
cursor.execute("CREATE TABLE t (dateDefinitionTest DATETIME)") 
cursor.execute("INSERT INTO t VALUES (?)", (datetime.datetime.now(),)) 
query = "SELECT dateDefinitionTest FROM t" 
cursor.execute(query) 
for row in cursor.fetchall(): 
    dt = datetime.datetime.strptime(row[0], "%Y-%m-%d %H:%M:%S.%f") 
    print(repr(dt)) 
    print(dt.strftime("%Y-%m-%d %H:%M:%S.%f")) 
cursor.close() 

,輸出:

datetime.datetime(2012, 11, 11, 16, 40, 26, 788966) 
2012-11-11 16:40:26.788966 
+0

我做了同樣的,但得到的錯誤:* * strptime()參數1必須是字符串,而不是緩衝區**。我使用Python 2.6 – Volatil3

+0

我做了什麼,我在另一個變量中分配了row [0]:** f = row [0] [:] **將_buffer_轉換爲str,然後** strptime **接受該值。 – Volatil3

+0

我的例子已經用Python 2.7進行了測試。 Python 2.6可能會返回一個緩衝區而不是一個字符串。 –

0
從得到

你的問題的根本原因是考慮到「緩衝」對象Sqlite數據庫作爲'string'對象,string對象具有encode()方法,但'buffer'對象沒有這個方法。 什麼你需要做的很簡單:只是轉換了「緩衝」對象到字符串對象,而且它並不難,只加一行在你的代碼:

tempString = STR([10])

_f = tempString.decode(「utf-8」)

今天我遇到了同樣的問題,並用google搜索引導我到這裏,但沒有找到合適的答案。所以在這裏提供。 sqlite記錄數據的類型是緩衝區還是字符串取決於我們如何構建我們的db表,以及sqlite版本和sqlite數據庫插件的版本,因此您的測試結果與Pedro Romano的不同。但是,只要添加下面這行:tempString = str(item [10]),它可以強制系統使用它作爲字符串。

相關問題