2025年3月14日 星期五 甲辰(龙)年 月十三 夜 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Python

python xlrd读取datetime类型数据

时间:12-10来源:作者:点击数:15

使用xlrd读取出来的时间字段是类似41410.5083333的浮点数,在使用时需要转换成对应的datetime类型,下面代码是转换的方法:

首先需要引入xldate_as_tuple函数:

  • from xlrd import xldate_as_tuple
  • #d是从excel中读取出来的浮点数
  • xldate_as_tuple(d,0)

xldate_as_tuple第二个参数有两种取值,0或者1,0是以1900-01-01为基准的日期,而1是1904-01-01为基准的日期。该函数返回的是一个元组,他的值类似:(year, month, day, hour, minute, nearest_second)

例子:

excel中E2单元格值为2018/05/27

  • from xlrd import xldate_as_tuple
  • result = xldate_as_tuple(ws['E2'].value,0)
  • print(result) # 结果(2018, 5, 27, 0, 0, 0)
  • from xlrd import xldate_as_tuple
  • result = xldate_as_tuple(ws.cell(row=2,column=5).value,0)
  • print(result) # 结果(2018, 5, 27, 0, 0, 0)

注意:该例子没有对第一行的数据进行处理。第一行数据作为key,其它行作为value,依次返回每行数据。 

  • import xlrd
  • from datetime import datetime
  • from xlrd import xldate_as_tuple
  • def get_excel_data(file): # 传入文件路径字符串即可,例如:get_excel_data('account.xlsx')
  • workbook = xlrd.open_workbook(file)
  • sheet = workbook.sheets()[0] # 读取第一个sheet
  • nrows = sheet.nrows # 行数
  • first_row_values = sheet.row_values(0) # 第一行数据
  • list = []
  • num = 1
  • for row_num in range(1, nrows):
  • row_values = sheet.row_values(row_num)
  • if row_values:
  • str_obj = {}
  • for i in range(len(first_row_values)):
  • ctype = sheet.cell(num, i).ctype
  • cell = sheet.cell_value(num, i)
  • 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 False
  • str_obj[first_row_values[i]] = cell
  • list.append(str_obj)
  • num = num + 1
  • return list

 

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐