Python 的xlrd库读取日期和数字时输出显示不正确问题解决
生活随笔
收集整理的這篇文章主要介紹了
Python 的xlrd库读取日期和数字时输出显示不正确问题解决
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
這里是要讀取的數據,有數字和日期,用xlrd庫讀取的時候會發現,數字后面多了個".0",讀取的日期變成了時間戳
def get_sheet1_data(excelDir, sheetName=None):# 1- excel 放到磁盤----把它加載到內存里workBook = xlrd.open_workbook(excelDir)# 2- excel 指定表sheet = workBook.sheet_by_name(sheetName)example_row = sheet.nrowsdata = []for _ in range(1, example_row):onerow = [sheet.row_values(_)[i] for i in range(len(sheet.row_values(1)))]data.append(onerow)return data執行結果:
[['iosapp0', 123456.0, 44906.0, 1.0, '', ''], ['', 123456.0, 44906.0, 0.0, '', ''], ['iosapp0', '', 44906.0, 0.0, '', ''], ['iosapp00', 123456.0, 44906.0, 0.0, '', '']]
這當然不是我們想要的結果:因此需要優化代碼
def get_sheet1_data(excelDir, sheetName=None):# 1- excel 放到磁盤----把它加載到內存里workBook = xlrd.open_workbook(excelDir)# 2- excel 指定表sheet = workBook.sheet_by_name(sheetName)example_row = sheet.nrowsdata = []for eachrow in range(1, example_row):onerow = []for eachcol in range(3):ctype = sheet.cell(eachrow, eachcol).ctypecell = sheet.cell_value(eachrow, eachcol)if ctype == 2 and cell % 1 == 0.0: # ctype為2且為浮點cell = int(cell) # 浮點轉成整型cell = str(cell) # 轉成整型后再轉成字符串,如果想要整型就去掉該行elif ctype == 3:date = datetime(*xldate_as_tuple(cell, 0))cell = date.strftime('%Y/%m/%d %H:%M:%S')elif ctype == 4:cell = True if cell == 1 else Falseonerow.append(cell)data.append(onerow)return data[['iosapp0', '123456', '2022/12/11 00:00:00'], ['', '123456', '2022/12/11 00:00:00'], ['iosapp0', '', '2022/12/11 00:00:00'], ['iosapp00', '123456', '2022/12/11 00:00:00']]
總結
以上是生活随笔為你收集整理的Python 的xlrd库读取日期和数字时输出显示不正确问题解决的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: AIFF和AIFF-C音频交换文件格式的
- 下一篇: websocket python爬虫_p