python 处理Excel 常见问题-读取Excel中时间
2017-10-17 17:38
761 查看
Excel 时间读取
当本地Excel存有一个时间列时,使用下面代码读取Excel
通过输出,可以看到 Excel 中的时间 ‘2017/10/17’,输出为一个数字,很明显这和我们需要的时间类型有出入。
那我们需要如何处理呢?
1.首先我们需要判断Excel单元格中的数据类型
通过上面的代码可以知道时间类型的ctype值为3
2.通过 xldate_as_tuple 方法,将读取的Excel值转换为 tuple,再通过datetime转换为转为时间类型
完整代码:
当本地Excel存有一个时间列时,使用下面代码读取Excel
import xlrd book = xlrd.open_workbook('demo.xls') sheet = book.sheet_by_name('Sheet1') for row in range(sheet.nrows): print(sheet.row_values(row)) # 输出: # ['时间'] # [43025.0]
通过输出,可以看到 Excel 中的时间 ‘2017/10/17’,输出为一个数字,很明显这和我们需要的时间类型有出入。
那我们需要如何处理呢?
1.首先我们需要判断Excel单元格中的数据类型
for row in range(sheet.nrows): for col in range(sheet.ncols): print(sheet.cell(row,col)) print('type',sheet.cell(row,col).ctype) # 输出: # text:'时间' # type 1 # xldate:43025.0 # type 3
通过上面的代码可以知道时间类型的ctype值为3
2.通过 xldate_as_tuple 方法,将读取的Excel值转换为 tuple,再通过datetime转换为转为时间类型
import datetime for row in range(sheet.nrows): for col in range(sheet.ncols): if sheet.cell(row,col).ctype == 3: date = xldate_as_tuple(sheet.cell(row,col).value,0) print(date) print(datetime.datetime(*date)) #输出: # (2017, 10, 17, 0, 0, 0) # 2017-10-17 00:00:00
完整代码:
import xlrd from xlrd import xldate_as_tuple import datetime book = xlrd.open_workbook('demo.xls') sheet = book.sheet_by_name('Sheet1') for row in range(sheet.nrows): 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) print(value) # 输出: # 时间 # 2017-10-17 00:00:00
相关文章推荐
- Trac - 常见问题 - 导出的csv格式文件在Excel中处理unix时间戳
- python 处理Excel 常见问题- 写入Excel
- Ado.Net读取Excel常见问题总结
- 关于python处理作Excel文件的一些问题,包括时间处理 (转)
- Ado.Net读取Excel常见问题总结
- 如何处理Oledb中EXCEL驱动读取EXCEL文件中字段长度大于255字符时出现的"数据截断"问题.
- Ado.Net读取Excel常见问题总结
- python 视频处理,提取视频相关帧,读取Excel
- Ado.Net读取Excel常见问题总结
- POI读取Excel常见问题
- php读取excel中的时间转换问题
- php读取excel中的时间转换问题
- Python常见问题处理
- POI处理Excel中时间问题
- Ado.Net读取Excel常见问题总结
- Ado.Net读取Excel常见问题总结
- python读取excel(Python处理xls)
- 如何处理ODBC中EXCEL驱动读取EXCEL文件中字段长度大于255字符时出现的"数据截断"问题.
- python-时间处理问题
- Ado.Net读取Excel常见问题总结