Python: xlrd discerning dates from floats

Antoni4040 picture Antoni4040 · Jul 24, 2013 · Viewed 12.4k times · Source

I wanted to import a file containing text, numbers and dates using xlrd on Python.

I tried something like:

if "/" in worksheet.cell_value:
    do_this
else:
    do_that  

But that was of no use as I latter discovered dates are stored as floats, not strings. To convert them to datetime type I did:

try:
    get_row = str(datetime.datetime(*xlrd.xldate_as_tuple(worksheet.cell_value(i, col - 1), workbook.datemode)))
except:
    get_row = unicode(worksheet.cell_value(i, col - 1))

I have an exception in place for when the cell contains text. Now i want to get the numbers as numbers and the dates as dates, because right now all numbers are converted to dates.

Any ideas?

Answer

chewynougat picture chewynougat · Aug 2, 2013

I think you could make this much simpler by making more use of the tools available in xlrd:

cell_type = worksheet.cell_type(row - 1, i)
cell_value = worksheet.cell_value(row - 1, i)

if cell_type == xlrd.XL_CELL_DATE:
    # Returns a tuple.
    dt_tuple = xlrd.xldate_as_tuple(cell_value, workbook.datemode)
    # Create datetime object from this tuple.
    get_col = datetime.datetime(
        dt_tuple[0], dt_tuple[1], dt_tuple[2], 
        dt_tuple[3], dt_tuple[4], dt_tuple[5]
    )
elif cell_type == xlrd.XL_CELL_NUMBER:
    get_col = int(cell_value)
else:
    get_col = unicode(cell_value)