1

So I have two dicts of time durations:

a = {hours: 13, minutes: 23}
b = {hours: 23, minutes: 42}

and I want to add them together so the final output would be:

{hours: 37, minutes: 5}

Is there any python built in library that can help me do this or do I have to write my own function?

Ibrahim Noor
  • 229
  • 3
  • 10
  • Do they each have just these two keys? – not_speshal Dec 15 '21 at 19:01
  • 3
    It's approximately 3 lines of code. It would be quicker to write it than to search for a library. The `datetime` module can do delta addition, but you'd have to convert to their format. – Tim Roberts Dec 15 '21 at 19:01

3 Answers3

2

The dictionary keys must be hashable so let's make them strings. Then, break it down into simple steps:

a = {'hours': 13, 'minutes': 23}
b = {'hours': 23, 'minutes': 42}

def add_times(a, b):
    m = a['minutes'] + b['minutes']
    h = (0 if m < 60 else 1) + a['hours'] + b['hours']
    return {'hours': h, 'minutes': m % 60}

print(add_times(a, b))

Output:

{'hours': 37, 'minutes': 5}
DarkKnight
  • 19,739
  • 3
  • 6
  • 22
2

Converting the dict values to datetime.timedelta values is trivial, after which you can easily add them.

>>> from datetime import timedelta
>>> timedelta(**a) + timedelta(**b)
datetime.timedelta(days=1, seconds=47100)

Converting the sum back to a dict is not so trivial, but still easy.

>>> x = timedelta(**a) + timedelta(**b)
>>> dict(zip(("hours", "minutes"), divmod(int(x.total_seconds())//60, 60)))
{'hours': 37, 'minutes': 5}
  1. Converting the total number of seconds into minutes
  2. Convert the minutes into hours and minutes
  3. Zip with the strings "hours" and "minutes" to create a sequence of tuples suitable for passing to dict.
chepner
  • 497,756
  • 71
  • 530
  • 681
1

Here's a solution that first sums together all time dicts and then moves over any extra hours from the minutes value.

def sum_times(*time_dicts):
    summed = {key: sum(d[key] for d in time_dicts) for key in time_dicts[0]}
    summed["hours"] += summed["minutes"] // 60
    summed["minutes"] %= 60
    return summed

With your example

a = {"hours": 13, "minutes": 23}
b = {"hours": 23, "minutes": 42}

print(sum_times(a, b))
{'hours': 37, 'minutes': 5}
Mandera
  • 2,647
  • 3
  • 21
  • 26