将数据格式的excel转换为日期格式python

use*_*024 14 python excel datetime xlrd

我正在从excel读取数据并使用python操作数据.但是日期将以整数形式出现.如何将日期转换回日期格式?

2015年5月15日即将发布,电话为42139.00

sae*_*gnu 17

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
Run Code Online (Sandbox Code Playgroud)

如JF Sebastian所述,这个答案仅适用于1900/03/01之后的任何日期

编辑:(回答@RK)

如果您excel_date是浮点数,请使用以下代码:

def floatHourToTime(fh):
    h, r = divmod(fh, 1)
    m, r = divmod(r*60, 1)
    return (
        int(h),
        int(m),
        int(r*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)
Run Code Online (Sandbox Code Playgroud)

  • @user2728024:`-2` 并不总是正确的,见[这个答案](http://stackoverflow.com/a/29387450/4279) (4认同)
  • `-2` 因为 Excel 日期的“开始日期”实际上是 1899 年的最后一天,并且 Excel 假定 1900 年是闰年(事实并非如此)。https://xlrd.readthedocs.io/en/latest/dates.html#dates-in-excel-spreadsheets (3认同)

zve*_*sky 6

该模块xlrd提供了xldate_as_tuple将Excel的数字日期格式转换为元组的功能(year, month, day, hour, minute, nearest_second)

然后,您可以datetime.datetime用于将元组转换为datetime-object。

from datetime import datetime
import xlrd

excel_date = 44032
python_date = datetime(*xlrd.xldate_as_tuple(excel_date, 0))
Run Code Online (Sandbox Code Playgroud)

  • `xlrd.xldate_as_tuple()` 的第二个参数是工作簿的“日期模式”(即基于 1900 或 1904 的日期)。最好直接从您的工作簿中传递它。(即工作簿的“datemode”属性)。https://xlrd.readthedocs.io/en/latest/dates.html#dates-in-excel-spreadsheets (2认同)