I'm reading excel files and writing them out as csv. A couple of columns contain dates which are formatted as float number in excel. All those fields need to get converted to a proper datetime (dd/mm/YY) before I wrote to CSV. I found some good articles on how that works in general, but struggling to get that working for all rows in a opened sheet at once. (Newbie in Python)
Code looks like below for now:
wb = xlrd.open_workbook(args.inname)
xl_sheet = wb.sheet_by_index(0)
print args.inname
print ('Retrieved worksheet: %s' % xl_sheet.name)
print outname
# TODO: Convert xldate.datetime from the date fileds to propper datetime
output = open(outname, 'wb')
wr = csv.writer(output, quoting=csv.QUOTE_ALL)
for rownum in xrange(wb.sheet_by_index(0).nrows):
wr.writerow(wb.sheet_by_index(0).row_values(rownum))
output.close()
I'm sure i have to change the "for rownum ...." line but I'm struggling doing it. I tried several options, which all failed.
thanks
The conversion from Excel to Python is quite simple:
Or to do the complete conversion to a string:
You need to go through the row before you write it out to file, converting values. You are right to identify that it is near the
for rownum
line:Exactly what you put in your
excel_time_to_string()
function is up to you - the answer by @MarkRansom has a reasonable approach - or you could use thexlrd
own package versions outlined in this answer.For instance:
* EDIT *
In response to request for help in comments after trying. Here's a more error-proof version of
excel_time_to_string()