[英]Read time from excel sheet using xlrd, in time format and not in float
我正在尝试从 excel 文件中读取一些数据。 其中一列具有格式为 HH:MM:SS 的时间值。 Xlrd 读取此时间并将其转换为浮点数。 我的 python 文件中有另一个时间值,我想将其与 excel 导入的时间值进行比较。 只要其中一个是“时间”而另一个是“浮动”,我就无法做到这一点。 有什么建议?
这就是我的 excel 文件的样子 -
Time L_6_1 PW_6_1 Tc_6_1 Te_6_1
0:00:00 10000 500 290 270
1:00:00 10000 600 290 270
2:00:00 10000 700 290 270
3:00:00 10000 800 290 270
4:00:00 10000 900 290 270
这就是我阅读这些数据的方式 -
wb=xlrd.open_workbook('datasheet.xls')
sh = wb.sheet_by_index(0)
timerange=sh.col_values(0)
print timerange
这是带有时间浮点值的输出 -
[u'Time', 0.0, 0.041666666666666664, 0.083333333333333301, 0.125, 0.166666666666
66699, 0.20833333333333301, 0.25, 0.29166666666666702, 0.33333333333333298, 0.37
5, 0.41666666666666702, 0.45833333333333298, 0.5, 0.54166666666666696, 0.5833333
3333333304, 0.625, 0.66666666666666696, 0.70833333333333304, 0.75, 0.79166666666
666696, 0.83333333333333304, 0.875, 0.91666666666666696, 0.95833333333333304]
xlrd 库有一个内置的 xldate_as_tuple() 函数,可以帮助您完成大部分工作:
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:])
Excel 将时间存储为一天的分数。 您可以将其转换为 Python 时间,如下所示:
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
如果您需要更高的精度,可以通过转换为毫秒或微秒并以这种方式创建时间来获得它。
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)
您可以使用xlrd的内置函数“xldate_as_datetime”(根据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)
#outage read data
outage_sheet =workbook2.sheet_by_index(day)
#str outage
outage =outage_sheet.cell_value(141,3)
#convert float time to hh:mm formate
x = int(outage*24*3600)
outage_a= time(x//3600,(x%3600)//60)
在这里,我将浮点值中断并将其转换为 HH:SS 格式
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.