Python讀取Excel,里面如果是日期,直接讀出來是float類型,無法直接使用。
通過判斷讀取表格的數據類型ctype,進一步處理。
返回的單元格內容的類型有5種:
ctype: 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error
ctype =sheet1.cell(iRow,iCol).ctype
參考示例如下:
比如excel里面時間格式的數據,python讀取時是float類型:

讀取后分別是:

如何變成界面顯示的格式
import os import xlrd import datetime from xlrd import xldate_as_tuple def test_Excel_date(excelFile): if os.path.exists(excelFile): data = xlrd.open_workbook(excelFile) table = data.sheets()[0] nrows = table.nrows # 行數 list1 = [] # Python讀Excel,返回的單元格內容的類型有5種: # ctype: 0 :empty; 1: string; 2 number; 3 : date; 4 : boolean,; 5: error # ctype = sheet1.cell(iRow, iCol).ctype #2021-01-01 對應的excel格式日期的float類型值 y_date = 44197.0 for i in range(1, nrows): ctype = table.cell(i, 1).ctype sCell = table.cell_value(i, 1) sCell = get_cell_value(sCell, ctype) print(sCell) def get_cell_value(sCell,ctype): ''' 獲取Excel日期格式單元格數據,Python讀Excel,返回的單元格內容的類型有5種: ctype: 0 :empty 1: string 2: number; 3: date; 4:boolean,; 5:error :param sCell: 單元格數據 :param ctype: 數據類型 :return: ''' # 44197.0 為2021-01-01對應的excel格式的float值,做輔助用 y_date = 44197.0 istime = 0 # 日期格式 if ctype == 3: # 日期數據只包含 %H:%M:%S,不包含%Y-%m-%d ,比如:01:31:52, # 23:59:59的float形式值為: 0.999988425925926,是小於的, if sCell < 1: istime = 1 sCell = y_date + sCell dtime = datetime.datetime(*xldate_as_tuple(sCell, 0)) strTime = dtime.strftime('%Y-%m-%d %H:%M:%S') # 只包含時間,沒有日期 比如:01:31:52 if istime == 1: return strTime[11:] else: # 44521.0000115741 對應:2021/1/1 9:28:11格式%Y-%m-%d %H:%M:%S # 44561.0 對應:2021/1/1 格式%Y-%m-%d return strTime else: return sCell if __name__=="__main__": imageFile = 'D:/test.xlsx' test_Excel_date(imageFile)
