将Excel中的数字日期格式转换为日期格式的Python代码

30

我正在使用Python从Excel读取数据并对其进行操作。但是日期显示为整数。如何将这些日期转换回日期格式?

5/15/2015 显示为 42139.00


对于 pandas 特定的解决方案,请参见 使用 pandas 转换 Excel 样式日期 - FObersteiner
2个回答

56
from datetime import datetime
excel_date = 42139
dt = datetime.fromordinal(datetime(1900, 1, 1).toordinal() + excel_date - 2)
tt = dt.timetuple()
print(dt)
print(tt)

正如J.F. Sebastian所提到的,此答案仅适用于1900/03/01之后的任何日期。

编辑:(回答@R.K)

如果您的excel_date是浮点数,请使用此代码:

from datetime import datetime

def floatHourToTime(fh):
    hours, hourSeconds = divmod(fh, 1)
    minutes, seconds = divmod(hourSeconds * 60, 1)
    return (
        int(hours),
        int(minutes),
        int(seconds * 60),
    )

excel_date = 42139.23213
dt = datetime.fromordinal(datetime(1900, 1, 1).toordinal() + int(excel_date) - 2)
hour, minute, second = floatHourToTime(excel_date % 1)
dt = dt.replace(hour=hour, minute=minute, second=second)

print(dt)
assert str(dt) == "2015-05-15 00:13:55"

1
它可以工作,但日期42139显示为2015-05-17 00:00:00而不是2015-05-15 00:00:00。 - user2728024
是的,-2解决了它。但很奇怪。 - user2728024
4
“-2”并不总是正确的,参见这个答案 - jfs
我有一个浮点格式的时间,例如42139.23213... 这也包括时间... 但是使用datetime.fromordinal()得到的输出是类似于dd/mm/yyyy 00:00:00 ... 我的时间总是0小时... 我该如何获取正确日期和时间? @saeedgnu - R.K
4
这是因为Excel日期的“开始日期”实际上是1899年最后一天,而Excel假设1900年是闰年(实际上不是),所以会出现-2的情况。请参考https://xlrd.readthedocs.io/en/latest/dates.html#dates-in-excel-spreadsheets。 - MinchinWeb
显示剩余3条评论

24

模块xlrd提供函数xldate_as_tuple,将Excel的数字日期格式转换为元组(年, 月, 日, 时, 分, 秒)

然后您可以使用datetime.datetime将元组转换为datetime对象。

from datetime import datetime
import xlrd

excel_date = 44032
python_date = datetime(*xlrd.xldate_as_tuple(excel_date, 0))

2
xlrd.xldate_as_tuple() 的第二个参数是工作簿的“datemode”(即基于1900年或1904年的日期)。最好直接从您的工作簿中传递它。(即您的工作簿的“datemode”属性)。https://xlrd.readthedocs.io/en/latest/dates.html#dates-in-excel-spreadsheets - MinchinWeb
xlrd.xldate_as_datetime(excel_date, 0) 和 datetime(*xlrd.xldate_as_tuple(excel_date, 0)) 相同。 - Lucas peret

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接