将时间间隔转换为秒

时间:2021-07-19 23:30:22

标签: python python-3.x

嗨,在几秒钟内返回值时遇到问题。现在它只是像这样返回多个 1 11111111111111111111111111111111111111。

应该返回 4220。

例如,我的输入是 1 10 20。

感谢任何帮助!

谢谢

# File: WS01p1.py
# Write a program that prompt to read a time interval in hours,
# minutes and seconds and prints the equivalent time in just seconds.

x,y,z = input("Input: ").split()
print(x*3600 + y*60 + z)

4 个答案:

答案 0 :(得分:3)

您需要将输入转换为 int 值而不是 str,后者在 x, y, z 之后分配给split()。您可以使用 str 函数将 int 对象转换为 int(<var>)。所以在这种情况下,它将是

print(int(x)*3600 + int(y)*60 + int(z))

答案 1 :(得分:2)

您的问题可以这样解释:

>>> print('1' * 7)
1111111

当您将字符串 s 与整数 n “相乘”时,您会得到 ns 副本的字符串。你需要的是一个整数乘以一个整数。可以用int()转换字符串,如:


vals = input('Input: ').split()
try:
    hrs  = int(vals[0])
    mins = int(vals[1])
    secs = int(vals[2])
    print(f'That is {hrs * 3600 + mins * 60 + secs} seconds')
except:
    print('Invalid input')

而且,顺便说一句,我不知道那是您的真实代码还是您拼凑在一起发布的内容,但如果是前者,您可能应该选择更好的变量名称。任何看到 x/y/z 的人几乎肯定会认为您正在使用 3D 笛卡尔坐标系而不是基于时间的东西做某事:-)

答案 2 :(得分:2)

您需要将 int 函数应用于从 split() 获得的每个值,以便将它们从以 10 为底的 str 值转换为 int 值。

>>> h, m, s = map(int, input("Input: ").split())
Input: 1 10 20
>>> print(h*3600 + m*60 + s)
4220

答案 3 :(得分:1)

x, y, z = map(int,input("Input:").split())

打印(x,y,z)

Input: 1 10 20

Output = 4220