Python程序查找当前时间和给定时间之间的差异
给定两个时间h1:m1
和h2:m2
表示 24 小时制格式的小时和分钟。当前时钟时间由h1:m1
给出。任务是以分钟为单位计算两次之间的差异,并以h:m
格式打印两次之间的差异。
例子:
Input : h1=7, m1=20, h2=9, m2=45
Output : 2 : 25
The current time is 7 : 20 and given time is 9 : 45.
The difference between them is 145 minutes.
The result is 2 : 25 after converting to h : m format.
Input : h1=15, m1=23, h2=18, m2=54
Output : 3 : 31
The current time is 15 : 23 and given time is 18 : 54.
The difference between them is 211 minutes.
The result is 3 : 31 after converting to h : m format.
Input : h1=16, m1=20, h2=16, m2=20
Output : Both times are same
The current time is 16 : 20 and given time is also 16 : 20.
The difference between them is 0 minutes.
As the difference is 0, we are printing “Both are same times”.
方法:
- 将两个时间都转换为分钟
- 在几分钟内找到差异
- 如果差值为 0,则打印“Both are same times”
- 否则将差异转换为 h : m 格式并打印
下面是实现。
# Python program to find the
# difference between two times
# function to obtain the time
# in minutes form
def difference(h1, m1, h2, m2):
# convert h1 : m1 into
# minutes
t1 = h1 * 60 + m1
# convert h2 : m2 into
# minutes
t2 = h2 * 60 + m2
if (t1 == t2):
print("Both are same times")
return
else:
# calculating the difference
diff = t2-t1
# calculating hours from
# difference
h = (int(diff / 60)) % 24
# calculating minutes from
# difference
m = diff % 60
print(h, ":", m)
# Driver's code
if __name__ == "__main__":
difference(7, 20, 9, 45)
difference(15, 23, 18, 54)
difference(16, 20, 16, 20)
# This code is contributed by SrujayReddy
输出:
2 : 25
3 : 31
Both are same times