Convert xldate to python datetime

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 error is shown below.

  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' 
+6
source share
2 answers

a[0] is xlrd.Cell , so you need to use a[0].value to access the contents of the cell.

In addition, you cannot unpack for year, month, day, hour, minute , because there are more than five values ​​in the received court (what about second ?) However, you can avoid this by unpacking the set (see, for example, What does * * (double star) and * (star) for parameters? ) instead of temporary variables:

 py_date = datetime.datetime(*xlrd.xldate_as_tuple(a[0].value, book.datemode)) 
+17
source

@jonrsharpe accepted answer works well. But this is cleaner:

 py_date = xlrd.xldate.xldate_as_datetime(a[0].value, book.datemode) 
+8
source

Source: https://habr.com/ru/post/975749/


All Articles