3

How can i add datetime.time objects to each other? Lets say i have:

import datetime as dt

a = dt.time(hour=18, minute=15)
b = dt.time(hour=0, minute=15)

#c = a+b???

c should be equal to datetime.time(hour=18, minute=30)

Edit:

I have a function that gets as arguments datetime.time objects and should return datetime.time object that is sum of passed arguments. As i am only dealing with hours and minutes i wrote this:

def add_times(t1, t2):
    hours = t1.hour + t2.hour
    minutes = t1.minute + t2.minute
    hours += minutes // 60
    minutes %= 60
    new_time = datetime.time(hour=hours, minute=minutes)
    return new_time

But it is a dirty way and i am sure there is a legit way of doing it.

How do i achieve that?

Quba
  • 4,776
  • 7
  • 34
  • 60
  • 6
    Take a look at [What is the standard way to add N seconds to datetime.time in Python?](http://stackoverflow.com/questions/100210/what-is-the-standard-way-to-add-n-seconds-to-datetime-time-in-python) - as this question has answers for adding multiple time variants and links to more examples – LinkBerest Mar 13 '16 at 17:11

1 Answers1

3

Adding timedeltas

You can add dt.timedeltas

import datetime as dt

a = dt.timedelta(hours=18, minutes=15)
b = dt.timedelta(hours=0, minutes=15)

a + b

datetime.timedelta(0, 66600)
tmthydvnprt
  • 10,398
  • 8
  • 52
  • 72