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?
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}
"hours"
and "minutes"
to create
a sequence of tuples suitable for passing to dict
.