0

I have the results for a SQL query in Python and I would like to convert this into a table with the appropriate data formats.

The results now:

(datetime.datetime(2014, 1, 13, 0, 0), Decimal('6.16'), Decimal('5.95'), Decimal('4.05')),

I would like the results to be:

13/01/14, 6.16, 5.95, 4.05

I have tried:

Data = list(conn.execute(# some query));
Stuff = [];
for row in Data:
Stuff.append([i for i in zip(time.strftime("%d %m %Y", row['day'].timetuple()), float(row['col1']), float(row['col2']), float(row['col3']))]);

But this seems to only zip by 1 character and not each element separated by ','. Is there a way to zip by delimiter? Or any alternative implementation to get the desired result.

EDIT

The solution previously suggested creates a list with [day, a1, a2, a3] i.e. n x 1 table vs n x 4 table i.e. day, a1, a2, a3 which is required. Is there any way to do this using zip or something similar?

2
  • 1
    what does conn.execute retuen before you cast it to a list? Commented Feb 17, 2014 at 8:07
  • Could you post your full code? It looks like you might be using some optional features such as DictCursor Commented Feb 17, 2014 at 9:12

2 Answers 2

1

You don't need zip. zip takes multiple lists and interleaves them

>>> zip('abc', '123')
[('a', '1'), ('b', '2'), ('c', '3')]

Just append the data straight to your Stuff list

Data = list(conn.execute(# some query));
Stuff = [];
for row in Data:
    Stuff.append([time.strftime("%d %m %Y", row['day'].timetuple()), float(row['col1']), float(row['col2']), float(row['col3'])])
Sign up to request clarification or add additional context in comments.

4 Comments

Yields an n x 1 array whereas a n x 4 array is required.
than your query returns just one row
@Blackholify which Python MySQL library are you using?
@PeterGibson using psycopg2 (postgresql). I've got the solution so it's fine now. Thanks
0
Stuff = []
for row in Data:
    Stuff.append([i for i in [row['day'], float(row['a1']), float(row['a2']), float(row['a3'])]]);

1 Comment

[i for i in [row['day'], float(row['a1']), float(row['a2']), float(row['a3'])]] this is equivalent (albeit slower) to just [row['day'], float(row['a1']), float(row['a2']), float(row['a3'])] which is what I proposed in my solution. If one works, then the other should also work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.