xlrd 读取excel 日期类型2种方式

有个excle表格需要做一些过滤然后写入数据库中,但是日期类型的cell取出来是个数字,于是查询了下解决的办法。


基本的代码结构

[python]  view plain  copy
  1. data = xlrd.open_workbook(EXCEL_PATH)  
  2. table = data.sheet_by_index(0)  
  3. lines = table.nrows  
  4. cols = table.ncols  
  5. print u'The total line is %s, cols is %s'%(lines, cols)  

读取某个单元格:

[python]  view plain  copy
  1. table.cell(x, y).value  
x:行

y:列    

行,列都是从0开始


*  时间类型的转换,把excel中时间转成python 时间(两种方式)

excel某个单元格   2014/7/8

[python]  view plain  copy
  1. xlrd.xldate_as_tuple(table.cell(2,2).value, 0)   #转化为元组形式  
  2. (201478000)  
  3. xlrd.xldate.xldate_as_datetime(table.cell(2,2).value, 1)   #直接转化为datetime对象  
  4. datetime.datetime(20187900)  
  5. table.cell(2,2).value   #没有转化  
  6. 41828.0  

源码查看:

[python]  view plain  copy
  1. # @param xldate The Excel number  
  2. # @param datemode 0: 1900-based, 1: 1904-based.  
  3. xldate_as_tuple(xldate, datemode)    
输入一个日期类型的单元格会返回一个时间结构组成的元组,可以根据这个元组组成时间类型

datemode 有2个选项基本我们都会使用1900为基础的时间戳


[python]  view plain  copy
  1. ##  
  2. # Convert an Excel date/time number into a datetime.datetime object.  
  3. #  
  4. # @param xldate The Excel number  
  5. # @param datemode 0: 1900-based, 1: 1904-based.  
  6. #  
  7. # @return a datetime.datetime() object.  
  8. #  
  9. def xldate_as_datetime(xldate, datemode)  
输入参数和上面的相同,但是返回值是一个datetime类型,就不需要在自己转换了


当然这两个函数都有相应的逆函数,把python类型变成相应的excle时间类型。​

本文出自 orangleliu笔记本 博客,请务必保留此出处 http://blog.csdn.net/orangleliu/article/details/38476881

猜你喜欢

转载自blog.csdn.net/shengerjianku/article/details/78938792