问题描述
最近在处理一个 excel 数据即的时候发现,如果表格中存在时间格式的数据时,常用方法:
import xlrd
readbook = xlrd.open_workbook('表格名.xls')
sheet = book.sheet_by_index(子表序列)
nrows = sheet.nrows
ncols = sheet.ncols
for row in range(sheet.nrows):
print(sheet.row_values(row))
发现,当读取到时间格式数据时,会打印一个浮点数,很不幸,这个浮点数不是时间戳(如果是时间戳那就太棒了,QAQ)
解决方法
我们需要判断表格中数据的数据类型: 时间的类型码为 3。
for row in range(sheet.nrows):
for col in range(sheet.ncols):
print(sheet.cell(row,col))
print('type',sheet.cell(row,col).ctype)
当遍历到时间格式数据时,返回的打印可以看到类型码为 3。
为了输出我们最开始的时间格式,我们需要借用 xldate_as_tuple 和 datetime。
首先引入两个库函数,然后转换即可
完整代码如下:
import xlrd
import numpy as np
from xlrd import xldate_as_tuple
import datetime
readbook = xlrd.open_workbook('./dataset/表格名.xlsx')
sheet = readbook.sheet_by_index(0)
nrows = sheet.nrows
ncols = sheet.ncols
for row in range(1, nrows):
element = []
for col in range(sheet.ncols):
value = sheet.cell(row, col).value
if sheet.cell(row, col).ctype == 3:
date = xldate_as_tuple(sheet.cell(row, col).value, 0)
value = datetime.datetime(*date)