Volatil3 Volatil3 - 1 year ago 159
Python Question

Python: convert buffer type of SQLITE column into string

I am new to Python 2.6. I have been trying to fetch date datetime value which is in

yyyy-mm-dd hh:m:ss
format back in my Python program. On checking the column type in Python I get the error:
'buffer' object has no attribute 'decode'
. I want to use the
function to split the date data and use it but I can't find how to convert a buffer to string. The following is a sample of my code (also available here):

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)
resultsetTasks = cursor.fetchall()
cursor.close() # closing the resultset
for item in resultsetTasks:
taskDetails = {}
_f = item[10].decode("utf-8")

The exception I get is:

'buffer' object has no attribute 'decode'

Answer Source

I am not exactly sure what your problem may be. The following is a working example of what you are trying to achieve, which hopefully will help you:

#!/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"
for row in cursor.fetchall():
    dt = datetime.datetime.strptime(row[0], "%Y-%m-%d %H:%M:%S.%f")
    print(dt.strftime("%Y-%m-%d %H:%M:%S.%f"))

which outputs:

datetime.datetime(2012, 11, 11, 16, 40, 26, 788966)
2012-11-11 16:40:26.788966
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download