Louis Etienne
Louis Etienne

Reputation: 1371

How to add hours and minutes between them

I want to do something like 2h35 + 0h56 in python. So this is what I tried :

>>> t1 = time(2, 35)
>>> t2 = time(0, 56)
>>> t3 = t1 + t2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.time'

How can I add times on a time in Python ? All the subjects on Stackoverflow ask for add times on a date, but I just need time no date!

Thanks for your help

Upvotes: 3

Views: 5886

Answers (2)

DevLounge
DevLounge

Reputation: 8447

from datetime import datetime
from dateutil.relativedelta import relativedelta

if __name__ == '__main__':

    t1 = datetime(year=2015, day=19, month=9, hour=2, minute=35)
    t2 = t1 + relativedelta(minutes=56)

    print(t2.strftime('%H:%m'))

You must specify a real date, but in your case, you are only interested in the hours and minutes, so you can just print them using strftime.

Upvotes: 3

cg909
cg909

Reputation: 2556

datetime.time represents absolute times and it doesn't make any sense to add e.g. 2:35 + 0:56.

See python time + timedelta equivalent. The solution there might help you.

Upvotes: 0

Related Questions