欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

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

发布时间:2024/3/26 45 豆豆
生活随笔 收集整理的这篇文章主要介绍了 解决python读取excel日期格式问题(日期变为数字,int变为double) 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

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 errorctype = sheet.cell(i, j).ctypecell = 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

总结

以上是生活随笔为你收集整理的解决python读取excel日期格式问题(日期变为数字,int变为double)的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。