I have a problem converting excel xldate to python datetime with the following code. Is this the right way to convert?
import xlrd
from datetime import datetime
book = xlrd.open_workbook("a.xls")
sh = book.sheet_by_index(0)
for rx in range(1,sh.nrows):
a = sh.row(rx)
print a
year, month, day, hour, minute = xlrd.xldate_as_tuple(a[0], book.datemode)
py_date = datetime.datetime(year, month, day, hour, minute)
a is printed -->
[xldate:40544.0, number:0.0, number:75.49847785316135, number:75.6401124106301]
The below error is shown
year, month, day, hour, minute = xlrd.xldate_as_tuple(a[0], book.datemode)
File "C:\Anaconda\Lib\site-packages\xlrd\xldate.py", line 67, in xldate_as_tuple
xldays = int(xldate)
TypeError: int() argument must be a string or a number, not 'Cell'
a[0]
is a xlrd.Cell
, so you need to use a[0].value
to access the cell content.
Also, you can't unpack to year, month, day, hour, minute
because there are more than five values in the tuple produced (what about second
?) However, you can avoid that by using tuple unpacking (see e.g. What does ** (double star) and * (star) do for parameters?) instead of the temporary variables:
py_date = datetime.datetime(*xlrd.xldate_as_tuple(a[0].value,
book.datemode))
@jonrsharpe's accepted answer works well. But this is cleaner:
py_date = xlrd.xldate.xldate_as_datetime(a[0].value, book.datemode)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With