'How to get time difference in mins in Python

I have a time representation as string in the format:

9:00 am
8:45 pm

e.g., 12-hour, no leading hour 0, am/pm suffix

I need to get the time difference in minutes between then and now.

The time is always in the future, so if it's 09:00 right now, 9:10 am is in 10 mins time and 8:50 am is in 23h, 50m.

I've been playing with strptime but I can't seem to work out how to get my parsed time and now() in a compatible format to do arithmetic on.



Solution 1:[1]

this is a variant using datetime.

the format string FMT = "%I:%M %p" is selected according to strptime#time.strftime. and as only datetime objects support differences, i use those only (using datetime.combine).

from datetime import datetime, timedelta

FMT = "%I:%M %p"
TODAY_DATE = datetime.today().date()

def to_datetime(t_str):
    return datetime.combine(TODAY_DATE, datetime.strptime(t_str, FMT).time())

NOW = to_datetime("9:00 am")
for t_str in ("9:10 am", "8:45 pm"):
    t = to_datetime(t_str)
    if t < NOW:
        t += timedelta(days=1)
    print(f"{t_str}, {(t - NOW)}, {(t - NOW).total_seconds() / 60:.0f} min")

it outputs:

9:10 am, 0:10:00, 10 min
8:45 pm, 11:45:00, 705 min

Solution 2:[2]

something like this, indeed with strptime:

from datetime import datetime

timeString1 = "9:00 am"
timeString2 = "8:45 pm"

format = '%I:%M %p'
datetime1 = datetime.strptime(timeString1, format)
datetime2 = datetime.strptime(timeString2, format)

minutes_diff = (datetime2 - datetime1).total_seconds() / 60.0

print(f"the time difference in minutes is: {minutes_diff}")

Solution 3:[3]

There are most likely better suited modules for that. But quick and dirty you could do:

def to_minutes(time_str)
    time, suffix = time_str.split(" ")
    hours, min = time.split(":")
    if suffix == "pm":
        hours+=12
    min = hours*60+min
    return min

time1 = to_minuntes("9:00 am")
time2 = to_minutes("8:45 pm")

diff = time2-time1
if diff < 0:
    diff+= 24*60
    
# and if necessary you can do a 
hours = diff //60
minutes = diff % 60

if hours > 0:
    final_diff = f"{hours}h {minutes}min"
else:
    final_diff = f"{minutes}min"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3