I’m having problems with the writerow() function. I have an object (orders_matrix) like this:
[[datetime.datetime(2008, 11, 20, 16, 0), 'AA', 'Buy', '100'],
[datetime.datetime(2008, 11, 28, 16, 0), 'AA', 'Sell', '100'],
[datetime.datetime(2009, 2, 17, 16, 0), 'AA', 'Buy', '100']]
and would like to write it in CSV format like this:
2008,11,20,AA,Buy,100,
2008,11,28,AA,Sell,100,
2009,2,17,AA,Buy,100,
I’ve tried to use the writerow() function in a for loop:
with open('orders.csv', 'w') as orders_file:
writer = csv.writer(orders_file)
for row in orders_matrix:
writer.writerow([row[:4], row[5:7], row[8:10], row[11:]])
but couldn’t be able to convert the datetime object and add the other elements. I’d like to know if it’s possible to do that and how.
You can use the year, month, day properties of the datetime object to get the related values. So, the last line might be changed with: