How to calculate time difference in python?

531 Views Asked by At

Example:

9:43 - 17:27 - how many hours and minutes elapsed between those times ?

2

There are 2 best solutions below

0
mozway On

Here is one approach to get the number of total minutes:

from datetime import datetime

s = '9:30 - 14:00 ; 14:30 - 16:30'

sum(((b-a).total_seconds()/60 for x in s.split(' ; ')
     for a,b in [list(map(lambda t: datetime.strptime(t, '%H:%M'), x.split(' - ')))]))

Output: 390.0

0
nigh_anxiety On

If you know that the time periods will never span midnight, then you could simply split the time strings with time.split(":") and do the math yourself with the hours and minutes.

However, the correct solution would be to import the datetime module and calculate the timedelta.

This example could be condensed. I intentionally made it verbose without knowing exactly how you're getting your inputs:

from datetime import datetime

times = [
    "9:30",
    "14:00",
    "14:30",
    "16:30"
]

#Just using today's date to fill in the values with assumption all times are on the same day.
year = 2022
month = 6
day = 9

date_times = []

for time in times:
    split_time = time.split(":")
    hour = split_time[0]
    minutes = split_time[1]
    timestamp = datetime.datetime.today(year=year, month=month, day=day, hour=hour, min=minutes)
    date_times.append(timestamp)

total_seconds = 0

for i in range(1, len(date_times), 2):
    delta = date_times[i] - date_times[i-1]  # The timedelta object returned will have days, seconds, milliseconds
    total_seconds += delta.days * 86400 + delta.seconds

hours = total_seconds // 3600  # Integer division
minutes = round((total_seconds % 3600) / 60)  # Change depending on if you want to round to nearest, or always up or down.