解决python读取excel日期格式问题(日期变为数字,int变为double)

本文介绍如何使用Python读取Excel数据,并针对整型和日期格式的数据进行正确的格式处理,避免数据展示错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

excel数据如下:
在这里插入图片描述

读取excel

# 读取excel文件
excel_data = xlrd.open_workbook(excel_path)
# 获取第一个sheet页
sheet = excel_data.sheet_by_index(0)
# 读取数据
for i in range(0, rows):
     for j in range(0, cols):
         print(sheet.cell(i,j).value)

打印结果

20200302.0
18560726646.0
43888.0

这里把整型数字和日期格式的数据都打印错了,不是我们想要的结果

解决格式问题

# 解决整型和日期型的格式问题
def format_excel(i,j):
    # 表格的数据类型
    # ctype: 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error
    ctype = sheet.cell(i, j).ctype
    cell = sheet.cell_value(i, j)
    if ctype == 2 and cell % 1 == 0:  # 如果是整形
        cell = int(cell)
    elif ctype == 3:
        # 转成datetime对象
        cell = xldate_as_datetime(cell, 0).strftime('%Y/%m/%d')
    return cell
  • 这样,再读取excel就格式就不会乱了
for i in range(0, rows):
     for j in range(0, cols):
         print(sheet.cell(i,j).value)
  • 打印结果
20200302
18560726646
2020/02/27
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值