Search code examples
pythonpython-3.xpython-2.7timedelta

How to add two maps of hours and minutes and add them in python


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?


Solution

  • 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.