[Python]xlrd 讀取excel 日期類型2種方式

來源:互聯網
上載者:User

標籤:excel   python   xlrd   

有個excle表格需要做一些過濾然後寫入資料庫中,但是日期類型的cell取出來是個數字,於是查詢了下解決的辦法。


基本的代碼結構

data = xlrd.open_workbook(EXCEL_PATH)table = data.sheet_by_index(0)lines = table.nrowscols = table.ncolsprint 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時間類型。?

本文出自 “orangleliu筆記本” 部落格,請務必保留此出處 http://blog.csdn.net/orangleliu/article/details/38476881

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.