Convert date from excel in number format to date format python [duplicate]

99封情书 提交于 2019-11-29 17:23:22

问题


This question already has an answer here:

  • How to convert a given ordinal number (from Excel) to a date 4 answers

I am reading data from excel and manipulating the data using python. But dates are coming as integers. How can I convert the dates back to date format?

5/15/2015 is coming as 42139.00


回答1:


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

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

EDIT: (in answer to @R.K)

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)



回答2:


The module xlrd provides a function xldate_as_tuple to convert Excel's numerical date format to a tuple (year, month, day, hour, minute, nearest_second).

You can then use datetime.datetime to convert the tuple into a datetime-object.

from datetime import datetime
import xlrd

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


来源:https://stackoverflow.com/questions/31359150/convert-date-from-excel-in-number-format-to-date-format-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!