django cursor fetchall change datetime.datetime and decimal stamp

259 views
Skip to first unread message

Shekar Tippur

unread,
Dec 23, 2015, 3:40:23 AM12/23/15
to Django users
Hello,

I am trying to use cursor to execute a sql and convert the results to a dictionary

def dictfetchall(cursor):
"Return all rows from a cursor as a dict"
columns = [col[0] for col in cursor.description]
return [
dict(zip(columns, row))
for row in cursor.fetchall()

This returns a value:

[{'created': datetime.datetime(2015, 12, 23, 4, 3, 53, 89779, tzinfo=<UTC>), 'to_address': 'Destination1', 'from_address': 'Source1', 'X': Decimal('0.0'), 'Y': Decimal('0.0')}]

I want it to be converted to a readable datetime format and take the decimal out. I want the output to be of the form

[{'created': 20150404T00:00:000000Z, 'to_address': 'Destination1', 'from_address': 'Source1', 'X': '0.0', 'Y': '0.0'}]

Appreciate any help on this.

- Shekar

Shekar Tippur

unread,
Dec 23, 2015, 6:30:49 PM12/23/15
to Django users
I got it to work ..

def dictfetchall(cursor):
"Returns all rows from a cursor as a dict"
fieldnames = [name[0] for name in cursor.description]
result = []
for row in cursor.fetchall():
rowset = []
for field in zip(fieldnames, row):
L=list(field)
if (isinstance(field[1], datetime.datetime)):
L[1]=L[1].strftime("%Y-%m-%d %H:%M:%S")
print (L[1])
if (isinstance(field[1], decimal.Decimal)):
L[1]=str(L[1])
rowset.append(L)
result.append(dict(rowset))
return result 
Reply all
Reply to author
Forward
0 new messages