Python Program to Find Difference between Current Time and Given Time (original) (raw)

Last Updated : 13 Nov, 2025

Given two times h1:m1 and h2:m2 in 24-hour clock format, where the current time is h1:m1, the task is to calculate the difference between these two times in minutes and display it in h:m format. For Example:

**Input: h1 = 7, m1 = 20, h2 = 9, m2 = 45
**Output: 2: 25
**Explanation: difference between 7:20 and 9:45 is 145 minutes, which equals 2 hours and 25 minutes.

Let's explore different methods to find difference between current time and given time.

Using datetime Module

This method uses Python’s built-in datetime module to easily calculate the time difference by converting both times into datetime objects.

Python `

from datetime import datetime, timedelta

h1, m1, h2, m2 = 7, 20, 9, 45

t1 = datetime.strptime("{}:{}".format(h1, m1), "%H:%M") t2 = datetime.strptime("{}:{}".format(h2, m2), "%H:%M")

if t2 < t1: t2 += timedelta(days=1)

diff = t2 - t1 h, m = divmod(diff.seconds // 60, 60) print("{} : {}".format(h, m))

`

**Explanation:

Using timedelta

This method uses Python’s timedelta class to represent both times as durations and directly find the difference between them.

Python `

from datetime import timedelta

h1, m1, h2, m2 = 7, 20, 9, 45

t1 = timedelta(hours=h1, minutes=m1) t2 = timedelta(hours=h2, minutes=m2)

if t2 < t1: t2 += timedelta(days=1)

diff = t2 - t1 h, m = divmod(diff.seconds // 60, 60) print("{} : {}".format(h, m))

`

**Explanation:

Using time Module

This method converts both times into total seconds using the time module and then calculates their difference in hours and minutes.

Python `

import time

h1, m1, h2, m2 = 7, 20, 9, 45

t1 = time.mktime((2025, 11, 12, h1, m1, 0, 0, 0, 0)) t2 = time.mktime((2025, 11, 12, h2, m2, 0, 0, 0, 0))

if t2 < t1: t2 += 86400

diff = t2 - t1 h, m = divmod(int(diff // 60), 60) print("{} : {}".format(h, m))

`

**Explanation:

Using Mathematical Calculation

This method manually converts hours and minutes into total minutes and computes the difference using simple arithmetic operations

Python `

h1, m1, h2, m2 = 7, 20, 9, 45

t1 = h1 * 60 + m1 t2 = h2 * 60 + m2

if t1 == t2: print("Both are same times") else: diff = t2 - t1 if t2 > t1 else (24 * 60 - (t1 - t2)) h = diff // 60 m = diff % 60 print("{} : {}".format(h, m))

`

**Explanation: