Home > Back-end >  How to add two maps of hours and minutes and add them in python
How to add two maps of hours and minutes and add them in python

Time:12-16

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?

CodePudding user response:

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}

CodePudding user response:

Converting the dict values to datetime.timedelta values is trivial:

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

Converting that 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}
  • Related