Home  >  Article  >  Backend Development  >  Python xlrd读取excel日期类型的2种方法

Python xlrd读取excel日期类型的2种方法

WBOY
WBOYOriginal
2016-06-10 15:14:071940browse

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

基本的代码结构

复制代码 代码如下:

data = xlrd.open_workbook(EXCEL_PATH) 
table = data.sheet_by_index(0) 
lines = table.nrows 
cols = table.ncols 
print u'The total line is %s, cols is %s'%(lines, cols) 

读取某个单元格:
复制代码 代码如下:

table.cell(x, y).value 

x:行
y:列   
行,列都是从0开始

*  时间类型的转换,把excel中时间转成python 时间(两种方式)
excel某个单元格   2014/7/8

复制代码 代码如下:

xlrd.xldate_as_tuple(table.cell(2,2).value, 0)   #转化为元组形式 
(2014, 7, 8, 0, 0, 0) 
xlrd.xldate.xldate_as_datetime(table.cell(2,2).value, 1)   #直接转化为datetime对象 
datetime.datetime(2018, 7, 9, 0, 0) 
table.cell(2,2).value   #没有转化 
41828.0 

源码查看:

复制代码 代码如下:

# @param xldate The Excel number 
# @param datemode 0: 1900-based, 1: 1904-based. 
xldate_as_tuple(xldate, datemode)  

输入一个日期类型的单元格会返回一个时间结构组成的元组,可以根据这个元组组成时间类型
datemode 有2个选项基本我们都会使用1900为基础的时间戳

复制代码 代码如下:

## 
# Convert an Excel date/time number into a datetime.datetime object. 

# @param xldate The Excel number 
# @param datemode 0: 1900-based, 1: 1904-based. 

# @return a datetime.datetime() object. 

def xldate_as_datetime(xldate, datemode)

输入参数和上面的相同,但是返回值是一个datetime类型,就不需要在自己转换了

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn