从excel表读取时间,使用xlrd,时间格式,而不是浮动 [英] Read time from excel sheet using xlrd, in time format and not in float

查看:1522
本文介绍了从excel表读取时间,使用xlrd,时间格式,而不是浮动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从excel文件中读取一些数据。其中一列具有格式为HH:MM:SS的时间值。 Xlrd读取此时间并将其转换为float。我在我的python文件中有另一个时间值,我想与excel导入的时间值进行比较。只要其中一个是时间,另一个是浮动,我就不能这样做。任何建议?



这是我的excel文件的样子 -

 时间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)
打印计时器

这是具有时间的浮点值的输出 -

  [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,095833333333333304]


解决方案

Excel存储时间作为一天的分数。您可以将其转换为Python时间,如下所示:

从$ datetime import time 

x = excel_time#一个float
x = int(x * 24 * 3600)#转换为秒数
my_time = time(x // 3600,(x%3600)// 60,x%60)#小时,分钟,秒

如果您需要更多精度,可以通过转换为毫秒或微秒来获取它,并创建一段时间。


I am trying to read some data from a excel file. One of the columns has time values in the format HH:MM:SS. Xlrd reads this time and converts it into float. I have another time values in my python file which I want to compare with the excel-imported time values. I am not able to do that as long as one of them is a "time" and the other is a "float". Any suggestions?

This is how my excel file looks like -

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

And this is how I am reading this data -

wb=xlrd.open_workbook('datasheet.xls')
sh = wb.sheet_by_index(0)
timerange=sh.col_values(0)
print timerange

This is the output with float values for time -

[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]

解决方案

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.

这篇关于从excel表读取时间,使用xlrd,时间格式,而不是浮动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆