Read time from excel sheet using xlrd, in time format and not in float

不问归期 提交于 2019-12-03 12:35:31

Excel stores times as fractions of a day. You can convert this to a Python time as follows:

from datetime import time

x = excel_time # a float
x = int(x * 24 * 3600) # convert to number of seconds
my_time = time(x//3600, (x%3600)//60, x%60) # hours, minutes, seconds

If you need more precision, you can get it by converting to milliseconds or microseconds and creating a time that way.

The xlrd library has a built-in, xldate_as_tuple() function for getting you most of the way there:

import xlrd
from datetime import time
wb=xlrd.open_workbook('datasheet.xls')

date_values = xlrd.xldate_as_tuple(cell_with_excel_time, wb.datemode)  

# date_values is now a tuple with the values: (year, month, day, hour, minute, seconds),
# so you just need to pass the last 3 to the time() function.
time_value = time(*date_values[3:])
    def convert_excel_time(t, hour24=True):
        if t > 1:
            t = t%1
        seconds = round(t*86400)
        minutes, seconds = divmod(seconds, 60)
        hours, minutes = divmod(minutes, 60)
        if hour24:
            if hours > 12:
                hours -= 12
                return "%d:%d:%d PM" % (hours, minutes, seconds)
            else:
                return "%d:%d:%d AM" % (hours, minutes, seconds)
        return "%d:%d:%d" % (hours, minutes, seconds)


print convert_excel_time(0.400983796)
print convert_excel_time(0.900983796, hour24=False)
print convert_excel_time(0.4006944444444)
print convert_excel_time(1.4006944444444)

You may use the inbuilt function of xlrd "xldate_as_datetime" (in accordance with the notification by Troy)

import xlrd
from datetime import time
wb=xlrd.open_workbook('datasheet.xls')

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