time_difference
以输入的形式读取开始时间和结束时间,计算并显示时差。
def time_difference(time1, time2):
start_hour, start_min, start_sec = time1
end_hour, end_min, end_sec = time2
lst = []
if len(time2) <= 0 and len(time1)<= 0:
return 0
else:
a = time2[0]-time1[0]
b = time2[1]-time1[1]
c = time2[2]-time1[2]
x = (a,b,c)
lst = []
for i in x:
if i not in lst:
lst.append(i)
return str(lst)
表达
time_difference((1, 2, 3), (13, 12, 11))
12:10:08'
这是预期的输出。但是如何添加":"
?并给出数字08
而不是8
也适用于返回time_difference((11, 46, 39), (22, 31, 17))
'10:44:38'
答案 0 :(得分:1)
def time_difference(time1, time2):
start_hour, start_min, start_sec = time1
end_hour, end_min, end_sec = time2
lst = []
if len(time2) <= 0 and len(time1)<= 0:
return 0
else:
a = time2[0]-time1[0]
b = time2[1]-time1[1]
c = time2[2]-time1[2]
x = (a,b,c)
lst = []
for i in x:
if i not in lst:
lst.append(i)
return ":".join("{:02d}".format(x) for x in lst)
示例:
>>> time_difference((1, 2, 3), (13, 12, 11))
'12:10:08'
字符串格式函数中的02d
将确保列表中的每个数字都填充为0,正好是2位数。
您必须明白,您不能简单地使用time2
中的值从time1
中减去值,因为这不是时间转换的完成方式。如果您想手动转换它,请使用merlin2011的答案。如果可能,您应该使用datetime
,这会考虑闰年和处理时间计算中的其他异常情况。
日期时间示例:
>>> from datetime import datetime
>>> str(datetime(2014, 04, 15, 22, 31, 17) - datetime(2014, 04, 15, 11, 46, 39))
'10:44:38'
答案 1 :(得分:0)
您可以通过返回元组来简化逻辑。此外,这是使用旧式%
运算符获取时间格式的另一种方法。
如果你想处理一般时间,你应该将所有内容转换为秒,进行计算,然后转换回来。
def time_difference(time1, time2):
totalSecond1 = time1[0] * 3600 + time1[1] * 60 + time1[2]
totalSecond2 = time2[0] * 3600 + time2[1] * 60 + time2[2]
diffSeconds = totalSecond2 - totalSecond1
hours = diffSeconds / 3600
diffSeconds -= hours * 3600
minutes = diffSeconds / 60
diffSeconds -= minutes * 60
print "%02d:%02d:%02d" % (hours,minutes,diffSeconds)
请注意,我已将该功能修改为print
而不返回,因为您的原始问题表示该功能应“计算并打印”。
答案 2 :(得分:0)
你应该像这样使用
def time_difference(time1, time2):
start_hour, start_min, start_sec = time1
end_hour, end_min, end_sec = time2
lst = []
if len(time2) <= 0 and len(time1)<= 0:
return 0
else:
a = str(time2[0]-time1[0])
b = str(time2[1]-time1[1])
c = str(time2[2]-time1[2])
if len(c) < 2:
c = "0" + c
if len(b) < 2:
b = "0" + b
x = (a,b,c)
lst = ""
for i in x:
lst += i + ":"
return lst[:-1]