Reading date as a string not float from excel using python xlrd

Kundan Kumar picture Kundan Kumar · Dec 20, 2012 · Viewed 38.8k times · Source

Possible Duplicate:
How do I read a date in Excel format in Python?

My date can be among any field in an excel file but when I read it using python xlrd its being read as a float. Is there a way to read all the excel cells as string?

I want to prepare a script to generate a file having all the values in excel file separated by a pipe but this date thing is creating problem.

Answer

jojo picture jojo · Dec 20, 2012

Excel stores dates as floats. If you want to convert them xlrd has a function to help you with this: xldate_as_tuple

An exmple:

import datetime, xlrd
book = xlrd.open_workbook("myfile.xls")
sh = book.sheet_by_index(0)
a1 = sh.cell_value(rowx=0, colx=0)
a1_as_datetime = datetime.datetime(*xlrd.xldate_as_tuple(a1, book.datemode))
print 'datetime: %s' % a1_as_datetime