-2

I have two time strings for start and end, as an example:

start = "9:30:00"
end = "11:14:00"

I want to subtract start from end to get the duration.

I have tried

new_start = datetime.strptime(start, '%H:%M:%S').strftime("%H:%M:%S")
new_end = datetime.strptime(end, '%H:%M:%S').strftime("%H:%M:%S")

I still get

unsupported operand type(s) for -: 'str' and 'str'

hc_dev
  • 8,389
  • 1
  • 26
  • 38
kevin wholley
  • 85
  • 1
  • 8
  • here is the answer i guess you are looking for https://stackoverflow.com/questions/3096953/how-to-calculate-the-time-interval-between-two-time-strings – Prashant Balotra Feb 08 '21 at 19:55
  • 3
    Does this answer your question? [How to calculate the time interval between two time strings](https://stackoverflow.com/questions/3096953/how-to-calculate-the-time-interval-between-two-time-strings) – hc_dev Apr 01 '21 at 22:19
  • Sure the subtraction order is appropriate to get the duration as intervall: "subtract start for end" ? – hc_dev Apr 01 '21 at 22:24

2 Answers2

1

To convert a time string to a time, use strptime.

...and that's it.

Don't convert the times to strings again with strftime before you have done your calculations with them.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
1

Please use the following way to subtract two time strings

     from datetime import datetime

     t1 = '10:33:26'
     t2 = '11:15:49'
     FMT = '%H:%M:%S'  # time format
     
     subtractedTime = datetime.strptime(t2, FMT) - datetime.strptime(t1, FMT)
hc_dev
  • 8,389
  • 1
  • 26
  • 38
  • 1
    Comments start with a `#` in Python ;-) – FObersteiner Feb 09 '21 at 06:08
  • Thanks @MrFuppes for reminding me. – Prashant Balotra Feb 12 '21 at 19:27
  • @PrashantBalotra You could [edit] and fix. At least reference the source which already answered: [How to calculate the time interval between two time strings](https://stackoverflow.com/questions/3096953/how-to-calculate-the-time-interval-between-two-time-strings). In the future please flag the question as __duplicate__. – hc_dev Apr 01 '21 at 22:21