python读取excel日期内容读出来是数字-Python读取Excel,日期列读出来是数字的处理...

Python读取Excel,里面如果是日期,直接读出来是float类型,无法直接使用。

通过判断读取表格的数据类型ctype,进一步处理。

返回的单元格内容的类型有5种:

ctype: 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error

ctype =sheet1.cell(iRow,iCol).ctype

参考示例如下:

1.准备一个Excel文件,文件名Book1.xlsx

20190704171648894098.png

从第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

importxlrdimportosimporttimefrom datetime importdatetimefrom xlrd importxldate_as_tupledefmain():

sPath=os.getcwd()

sFile= "Book1.xlsx"wb= xlrd.open_workbook(filename=sPath + "\" +sFile)

sheet1=wb.sheet_by_index(0)

nrows=sheet1.nrows

ncols=sheet1.ncolsfor iRow in range(1,nrows):for iCol inrange(ncols):

sCell=sheet1.cell_value(iRow,iCol)#Python读Excel,返回的单元格内容的类型有5种:

#ctype: 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error

ctype =sheet1.cell(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:ifisVaildDate(sCell):

t1= time.strptime(sCell, "%Y-%m-%d")

sDate= changeStrToDate(t1,"yyyy-mm-dd")print(sDate)else:pass

defformatDay(sDay,sFormat):

sYear=str(sDay.year)

sMonth=str(sDay.month)

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 + "-" +sDayreturnsFormatDay"""功能:判断是否为日期"""

defisVaildDate(sDate):try:if ":" insDate:

time.strptime(sDate,"%Y-%m-%d %H:%M:%S")else:

time.strptime(sDate,"%Y-%m-%d")returnTrueexcept:returnFalse"""功能:把字符串格式的日期转换为格式化的日期,如把2019-7-1转换为2019-07-01"""

defchangeStrToDate(sDate,sFormat):

sYear=str(sDate.tm_year)

sMonth=str(sDate.tm_mon)

sDay=str(sDate.tm_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 + "-" +sDayreturnsFormatDayif __name__ == "__main__":

main()

3.执行结果:

20190704171649294504.png

原文地址:https://www.cnblogs.com/SH170706/p/11133525.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值