RPA-使用Python读取Excel日期结果为数字时的转换处理方法

不知道大家有没有遇到过,在使用Python读取 Excel的行列或是单元格时,如果其内容是日期格式的,而打印出来后却不是日期,而是一串数字,如下图:


我们期望这个日期解析出来是:1919/1/20以及2019/11/20,而结果却是数字6960.0和43789.0,这是什么原因呢?这个数字又是什么呢?
其实这是以1900年为原点,到指定日期经过的天数。

想要将数字转换为日期,可以通过 xlrd 中的 xldate_as_tuple 方法可以将数字转换为日期,在代码块中添加代码进行转换,参考代码如下:

from datetime import datetime
from xlrd import xldate_as_tuple

ExcelDate = []
for date in lv_1:
print('数字日期:',date,end = ' ') 
new_date =str ( datetime ( * xldate_as_tuple(date,0)))#使用xldate_as_tuple方法转换,并将转换后的值变为string类型
print('转换后日期:',new_date) 
new_date = new_date[0:10] # 取日期部分
print('最终打印效果:',new_date)

ExcelDate.append(new_date)

print('最终得到的日期列表', ExcelDate ) 


效果:


当然,如果使用pandas库读取Excel就不会遇到这种情况了,【读取Excel】组件使用便是pandas的read_excel方法:

 免费下载试用:https://support.i-search.com.cn/

猜你喜欢

转载自www.cnblogs.com/isearch/p/11897803.html