首页 > 解决方案 > convert a time string to time

问题描述

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'

标签: pythondatetimetimeformat

解决方案


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.


推荐阅读