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


I am trying to get the variable stop_date to take away the value from the variable start_date to get the return output as 30.

When I try this:

start_date = '20151231171500'
stop_date = '20151231174500'
test = stop_date - start_date
print test

It give me an error: TypeError: unsupported operand type(s) for -: ‘str’ and ‘str’

The error are jumping on this line:

test = stop_date - start_date

I am trying to convert from date format into the minutes for the remaining time.

Asked By: user4394017



start_date and stop_date are strings, which don’t support the - operator. If you want to compute their (numerical) difference, define them as integers, i.e.

start_date = 20151231171500
stop_date = 20151231174500

or cast them to int:

test = int(stop_date) - int(start_date)

Caveat: the difference of these numbers would be 3000, not 30. Not sure why you expect 30.

edit: so much for why you cannot substract a string from a string. To compute the actual time difference between dates, please see Martijn’s answer.

Answered By: timgeb

You have strings, not datetime objects. If you want to treat the strings as datetime information, you’ll need to parse them into datetime objects:

from datetime import datetime

start_date = datetime.strptime(start_date, '%Y%m%d%H%M%S')
stop_date = datetime.strptime(stop_date, '%Y%m%d%H%M%S')

difference = stop_date - start_date

The resulting objects is a datetime.timedelta() instance, which models a time duration in terms of days and seconds:

>>> from datetime import datetime
>>> start_date = '20151231171500'
>>> stop_date = '20151231174500'
>>> start_date = datetime.strptime(start_date, '%Y%m%d%H%M%S')
>>> stop_date = datetime.strptime(stop_date, '%Y%m%d%H%M%S')
>>> start_date, stop_date
(datetime.datetime(2015, 12, 31, 17, 15), datetime.datetime(2015, 12, 31, 17, 45))
>>> difference = stop_date - start_date
>>> difference
datetime.timedelta(0, 1800)
>>> difference.seconds

Printing a timedelta object formats it to show days (if there are any), hours, minutes and seconds:

>>> print difference

or you can calculate the number of minutes by dividing by 60. If you use the divmod() function you get the remainder in seconds as well:

>>> minutes, seconds = divmod(difference.seconds, 60)
>>> minutes, seconds
(30, 0)

Do the same again with the minutes you calculated like this to get hours:

>>> hours, minutes = divmod(minutes, 60)
>>> hours, minutes, seconds
(0, 30, 0)

Note that you would use the timedelta.total_seconds() method to include the days as well, if you wanted to record the total number of hours over 24.

Answered By: Martijn Pieters
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.