Python xlrd读取excel日期类型的2种方法
作者:junjie 时间:2021-06-28 02:12:53
有个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,日期类型
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python教程教你如何去除背景
2023-01-08 17:19:40
![](https://img.aspxhome.com/file/2023/6/99326_0s.png)
Python运行DLL文件的方法
2021-12-25 15:23:21
一篇文章彻底搞懂Python切片操作
2021-10-11 18:23:07
![](https://img.aspxhome.com/file/2023/5/101575_0s.jpg)
pandas 层次化索引的实现方法
2023-11-24 19:04:02
python爬虫入门教程--利用requests构建知乎API(三)
2022-12-17 14:42:45
![](https://img.aspxhome.com/file/2023/1/117861_0s.jpg)
一实用的table内容排序Javascript类库
2008-11-02 15:03:00
解析PHP中一些可能会被忽略的问题
2023-09-05 14:07:37
HTML在线编辑器任意设置字号大小
2007-08-29 19:55:00
Python获取暗黑破坏神3战网前1000命位玩家的英雄技能统计
2023-09-25 13:01:40
![](https://img.aspxhome.com/file/2023/3/100863_0s.gif)
php使用ZipArchive函数实现文件的压缩与解压缩
2023-07-12 20:58:19
利用Python如何画一颗心、小人发射爱心
2021-01-11 09:11:50
![](https://img.aspxhome.com/file/2023/7/95887_0s.png)
Python画柱状统计图操作示例【基于matplotlib库】
2021-04-06 21:53:50
![](https://img.aspxhome.com/file/2023/2/97262_0s.png)
Python随机生成数模块random使用实例
2022-08-04 21:04:48
python标识符命名规范原理解析
2023-05-28 04:06:42
Pandas使用Merge与Join和Concat分别进行合并数据效率对比分析
2023-03-13 12:14:01
![](https://img.aspxhome.com/file/2023/6/90926_0s.png)
Python 元组(Tuple)操作详解
2023-06-28 15:36:39
![](https://img.aspxhome.com/file/2023/3/59133_0s.png)
浅析python打包工具distutils、setuptools
2021-03-30 14:45:14
![](https://img.aspxhome.com/file/2023/2/65132_0s.png)
使用基于Python的Tornado框架的HTTP客户端的教程
2023-05-15 06:50:43
Python中的pack和unpack的使用
2023-08-20 05:24:33
python 包之 threading 多线程
2021-06-03 19:54:41