Skip to content
Advertisement

Converting a .xlsx date into a normal date

I’ve been using xlrd3 to manage a .xlsx spreadsheet through python. When I’m given the value of the cell the date should be in, it gives me 44295, which should be 09/04/2021.

I understand that this is because of the format excel stores dates as, so I’ve been using the xldate_as_datetime function in this way:

 lastsold = itemworksheet.cell_value(i,32)
 lastsold_date = xlrd3.xldate_as_datetime(lastsold,0)
 lastsold_object = lastsold_date.date()
 lastsold_string = lastsold_object.isoformat()

(i is an interable from a ‘for’ loop)

When the code is (lastsold,0) I get the error

'<' not supported between instances of 'str' and 'int'

And when the code is (lastsold,1) I get the error.

invalid literal for int() with base 10: ''

What can I do so I can get the date in the format 09/04/2021 in python?

Advertisement

Answer

I have tested with below code and it works well. Please check it.

import xlrd

book = xlrd.open_workbook("test.xlsx")
first_sheet = book.sheet_by_index(0)

val = first_sheet.cell_value(0, 1)
lastsold_date = xlrd.xldate_as_datetime(val, 1)
obj = lastsold_date.date()

print(obj.isoformat())
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement