1

I want to add two time values t1 and t2 in format 'HH:MM:SS'.

t1 ='12:00:00'
t2='02:00:00'

t1+t2 should be 14:00:00

I tried t1+t2. But as t1 & t2 are im string format the output was concatenation 12:00:00 02:00:00.

So I tried to convert in datetime.datetime.strptime().time() object like

t1 = datetime.datetime.strptime('12:00:00', '%H:%M:%S').time()
t2 = datetime.datetime.strptime('02:00:00', '%H:%M:%S').time()

but gives error

TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.time'

How can I get this to work?

enter image description here

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
priya_a
  • 39
  • 1
  • 2
  • Add the `datetime` objects, not the `time` objects. – juanpa.arrivillaga Apr 18 '17 at 18:25
  • 2
    Possible duplicate of [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) – juanpa.arrivillaga Apr 18 '17 at 18:27
  • @juanpa.arrivillaga, this is not a duplicate of the linked question since it already has a numbers of seconds to add. The OP has two time stamps. – Stephen Rauch Apr 19 '17 at 00:13

1 Answers1

4

You can not directly add two time() variables. This is due to the fact that these time variables are not durations. They are the time of day. You can however turn a time variable into a duration by subtracting the zero element for this operation from the time variable (i.e. midnight).

Test Code:

import datetime as dt
t1 = dt.datetime.strptime('12:00:00', '%H:%M:%S')
t2 = dt.datetime.strptime('02:00:00', '%H:%M:%S')
time_zero = dt.datetime.strptime('00:00:00', '%H:%M:%S')
print((t1 - time_zero + t2).time())

Results:

14:00:00
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135