Python3读取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

  参考示例如下:

  比如excel里面时间格式的数据,python读取时是float类型:

  

  读取后分别是:

  

  如何变成界面显示的格式

   

import os
import xlrd
import datetime
from xlrd import xldate_as_tuple

def test_Excel_date(excelFile):
    if os.path.exists(excelFile):
        data = xlrd.open_workbook(excelFile)
        table = data.sheets()[0]
        nrows = table.nrows  # 行数
        list1 = []
        # Python读Excel,返回的单元格内容的类型有5种:
        # ctype: 0 :empty;  1: string; 2 number;    3 : date;  4 : boolean,; 5: error
        # ctype = sheet1.cell(iRow, iCol).ctype
        #2021-01-01 对应的excel格式日期的float类型值
        y_date = 44197.0
        for i in range(1, nrows):
            ctype = table.cell(i, 1).ctype
            sCell = table.cell_value(i, 1)
            sCell = get_cell_value(sCell, ctype)
            print(sCell)

def get_cell_value(sCell,ctype):
    '''
    获取Excel日期格式单元格数据,Python读Excel,返回的单元格内容的类型有5种:
    ctype:
    0 :empty
    1: string
    2: number;
    3: date;
    4:boolean,;
    5:error
    :param sCell: 单元格数据
    :param ctype: 数据类型
    :return:
    '''
    # 44197.0 为2021-01-01对应的excel格式的float值,做辅助用
    y_date = 44197.0
    istime = 0
    # 日期格式
    if ctype == 3:
        # 日期数据只包含  %H:%M:%S,不包含%Y-%m-%d ,比如:01:31:52,
        # 23:59:59的float形式值为:  0.999988425925926,是小于的,
        if sCell < 1:
            istime = 1
            sCell = y_date + sCell
        dtime = datetime.datetime(*xldate_as_tuple(sCell, 0))
        strTime = dtime.strftime('%Y-%m-%d %H:%M:%S')
        # 只包含时间,没有日期 比如:01:31:52
        if istime == 1:
            return strTime[11:]
        else:
            # 44521.0000115741 对应:2021/1/1 9:28:11格式%Y-%m-%d %H:%M:%S
            # 44561.0   对应:2021/1/1 格式%Y-%m-%d
            return strTime
    else:
        return sCell

if __name__=="__main__":
    imageFile = 'D:/test.xlsx'
    test_Excel_date(imageFile)

  

原文地址:https://www.cnblogs.com/shaosks/p/15702261.html