Python读取Excel,⽇期列读出来是数字的处理
Python读取Excel,⾥⾯如果是⽇期,直接读出来是float类型,⽆法直接使⽤。
通过判断读取表格的数据类型ctype,进⼀步处理。
返回的单元格内容的类型有5种:
ctype: 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error
ctype =ll(iRow,iCol).ctype
参考⽰例如下:
1.准备⼀个Excel⽂件,⽂件名Book1.xlsx
从第2⾏的第1列开始向右,分别是2019年的7⽉的1、2、3、4⽇,2019-07-01、2019-07-02、2019-07-03、2019-07-04 A列单元格的类型:date
B列单元格的类型:Text
C列单元格的类型:Text
D列单元格的类型:Custom⾥的⼀种⽇期格式
2.Python⽂件,ReadExcelDemo.py,代码如下:
#! -*- coding utf-8 -*-
#! @Time  :2019/7/4 15:46
#! Author :Frank Zhang
#! @File  :ReadExcelDemo.py
#!SoftWare PyChart 5.0.3
#! Python Version 3.7
import xlrd
import os
import time
from datetime import datetime
from xlrd import xldate_as_tuple
def main():
sPath = os.getcwd()
sFile = "Book1.xlsx"
wb = xlrd.open_workbook(filename=sPath + "\\" + sFile)
sheet1 = wb.sheet_by_index(0)
nrows = ws
ncols = ls
for iRow in range(1,nrows):
for iCol in range(ncols):
sCell = ll_value(iRow,iCol)
#Python读Excel,返回的单元格内容的类型有5种:
#ctype: 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error
ctype = ll(iRow,iCol).ctype
#ctype =3,为⽇期
if ctype == 3:
date = datetime(*xldate_as_tuple(sCell, 0))
cell = date.strftime('%Y-%m-%d')              #('%Y/%m/%d %H:%M:%S')
print(cell)
#ctype =1,为字符串
elif ctype == 1:
if isVaildDate(sCell):
t1 = time.strptime(sCell, "%Y-%m-%d")
sDate = changeStrToDate(t1,"yyyy-mm-dd")
print(sDate)
else:
pass
def formatDay(sDay,sFormat):
sYear = ar)
sMonth = h)
sDay = str(sDay.day)
if sFormat == "yyyy-mm-dd":
sFormatDay = sYear +"-" +sMonth.zfill(2)+"-" +sDay.zfill(2)
elif sFormatStyle == "yyyy/mm/dd":
sFormatDay = sYear +"/" +sMonth.zfill(2)+"/" +sDay.zfill(2)
else:
sFormatDay = sYear+"-" + sMonth + "-" + sDay
return sFormatDay
"""
功能:判断是否为⽇期
"""
def isVaildDate(sDate):
try:
if":"in sDate:
time.strptime(sDate, "%Y-%m-%d %H:%M:%S")
else:
time.strptime(sDate, "%Y-%m-%d")
return True
except:
python怎么读取excel某一列return False
"""
功能:把字符串格式的⽇期转换为格式化的⽇期,如把2019-7-1转换为2019-07-01 """
def changeStrToDate(sDate,sFormat):
sYear = _year)
sMonth = _mon)
sDay = _mday)
if sFormat == "yyyy-mm-dd":
sFormatDay = sYear +"-" +sMonth.zfill(2)+"-" +sDay.zfill(2)
elif sFormatStyle == "yyyy/mm/dd":
sFormatDay = sYear +"/" +sMonth.zfill(2)+"/" +sDay.zfill(2)
else:
sFormatDay = sYear+"-" + sMonth + "-" + sDay
return sFormatDay
if__name__ == "__main__":
main()
3.执⾏结果:

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。