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

早上好,给您新鲜的问候,温暖的祝福,清晨,美好的开端,祝您今天精神振奋,精力充沛,心情愉快,一切都很好!

有个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时间类型。

到此这篇关于Python xlrd读取excel日期类型的2种方法就介绍到这了。行动才能送你到达你想要的彼岸,好好加油吧,时间如白驹过隙。更多相关Python xlrd读取excel日期类型的2种方法内容请查看相关栏目,小编编辑不易,再次感谢大家的支持!

您可能有感兴趣的文章
Python自动化运维-使用Python脚本监控华为AR路由器关键路由变化

Python自动化运维-netmiko模块设备自动发现

Python自动化运维—netmiko模块连接并配置华为交换机

Python自动化运维-利用Python-netmiko模块备份设备配置

Python3内置模块之json编码解码方法详解