📜  Python程序查找当前时间和给定时间之间的差异

📅  最后修改于: 2022-05-13 01:54:43.475000             🧑  作者: Mango

Python程序查找当前时间和给定时间之间的差异

给定两个时间h1:m1h2:m2表示 24 小时制格式的小时和分钟。当前时钟时间由h1:m1给出。任务是以分钟为单位计算两次之间的差异,并以h:m格式打印两次之间的差异。

例子:

方法:

  • 将两个时间都转换为分钟
  • 在几分钟内找到差异
  • 如果差值为 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