且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将日期从Excel以数字格式转换为日期格式python

更新时间:2023-11-29 13:04:04

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

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

As mentioned by J.F. Sebastian, this answer only works for any date after 1900/03/01

编辑:(以@表示) RK)

(in answer to @R.K)

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

If your excel_date is a float number, use this code:

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)