python怎么读出当前时间_Python读取Excel,日期列读出来是数字的处理
Python讀取Excel,里面如果是日期,直接讀出來(lái)是float類型,無(wú)法直接使用。
通過(guò)判斷讀取表格的數(shù)據(jù)類型ctype,進(jìn)一步處理。
返回的單元格內(nèi)容的類型有5種:
ctype: 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error
ctype =sheet1.cell(iRow,iCol).ctype
參考示例如下:
1.準(zhǔn)備一個(gè)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
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,返回的單元格內(nèi)容的類型有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"""功能:把字符串格式的日期轉(zhuǎn)換為格式化的日期,如把2019-7-1轉(zhuǎn)換為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.執(zhí)行結(jié)果:
原文地址:https://www.cnblogs.com/SH170706/p/11133525.html
總結(jié)
以上是生活随笔為你收集整理的python怎么读出当前时间_Python读取Excel,日期列读出来是数字的处理的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 如何让不玩游戏不画图的电脑流畅至极电脑画
- 下一篇: 一瓶啤酒多少毫升