Skip to main content
 首页 » 编程设计

Python xlrd 读取 DateTime 为序列号

2025年05月04日11xing901022

我有一个日期时间格式的 Excel。但是当我阅读表格时,它显示为序列号。

例如,在工作表中它是 08/03/2015 但 xlrd 读取为 42219。

代码很简单

workbook = xlrd.open_workbook(file_contents=excel_contents) 
the_sheet = workbook.sheet_names()[0] 
number_of_rows = the_sheet.nrows - 1 
curr_row = 0 
data = [] 
 
while curr_row < number_of_rows: 
    curr_row += 1 
    air_date = the_sheet.cell_value(curr_row, 1) 
    air_time = the_sheet.cell_value(curr_row, 2) 
    schedule_time = '{}:{}'.format(air_date, air_time) 
    unaware = datetime.strptime(schedule_time, '%m/%d/%Y:%I:%M %p')  

我用来在 Python 中转换为 datetime 的 air_date 被炸掉了,因为格式不同。

这是示例 excel。

这是我得到的错误

builtins.ValueError ValueError: time data '42219.0:06:00 AM' does not match format '%m/%d/%Y:%I:%M %p'

请您参考如下方法:

看来您需要使用 xldate_as_tuple 将 excel 格式转换为 python 格式(参见 documentation 和 this already existing question,您可以在其中找到将日期转换为 python 的格式。

xldate_as_tuple :

Convert an Excel number (presumed to represent a date, a datetime or a time) into a tuple suitable for feeding to datetime or mx.DateTime constructors.