TypeError:float()参数必须是字符串或time.sleep()中的数字

时间:2015-01-20 07:57:25

标签: python

我的间隔时间为30秒,我将在time.sleep()中的Python脚本中添加30秒。

interval="00:00:30"
interval_seconds=interval.split(":",2)
interval_seconds[2]=interval_seconds
print interval_seconds

现在我在我的代码中使用此值:

count=2
while(count>0):
    print "inside while"
    time.sleep(float(interval_seconds))
    count=count-1

在运行时我收到此错误:

time.sleep(float(interval_seconds))
TypeError: float() argument must be a string or a number

3 个答案:

答案 0 :(得分:3)

interval_seconds[2]=interval_seconds

它仍然是list,因此您无法在float()函数中添加列表。您必须将要放入的元素放在float()中。所以在你的情况下解决方案是;

time.sleep(float(interval_seconds[2]))

完整代码;

interval="00:00:30"
interval_seconds=interval.split(":",2)
print interval_seconds

count=2
while(count>0):
    print "inside while"
    time.sleep(float(interval_seconds[2])) 
    count=count-1

答案 1 :(得分:2)

这是您的代码的问题:

interval="00:00:30"
# creates a list with all elements describing the time
# you don't need the second argument, as you intend to split on
# all ':'
interval_seconds=interval.split(":",2)
# this does *not* do what you expect.
# it assigns a list to 'interval seconds' list at index 2
interval_seconds[2]=interval_seconds
# now you have nested lists :(
print interval_seconds

请改为尝试:

interval="00:00:30"
# take only third element (index 2)
interval_seconds=interval.split(":")[2]
print interval_seconds

这只需几秒钟。

提示:您可能需要使用timedelta来描述一定的时间:

>>> from datetime import timdelta
>>> interval="00:00:30"
>>> hours, minutes, seconds = interval.split(':')
>>> td = timedelta(hours=int(hours), minutes=int(minutes), secotimedeltands=int(seconds))
>>> td
datetime.timedelta(0, 30)
>>> td.seconds
30

您可以使用列表解析显式多次明确地转换为int

>>> hours, minutes, seconds = [int(x) for x in interval.split(':')]

map

>>> hours, minutes, seconds = map(int, interval.split(':'))

......只是想清楚

答案 2 :(得分:2)

我犯了错误。它不应该是以前的代码,而应该是

interval="00:00:30"
interval_seconds=interval.split(":",2)
interval_seconds=interval_seconds[2]
print interval_seconds

在我的代码中,它应该是

time.sleep(float(str(interval_seconds)))

然后它的工作正常。enter code here