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

1,100 views
Skip to first unread message

markg

unread,
May 17, 2011, 5:36:53 PM5/17/11
to robotframework-users
I've created a very simple test library (python) to take the current
hour returned by GET TIME and converted it to 12-hour format. I call
the library via the following:

${year} ${month} ${day} ${hour} ${min} Get Time year month day
hour min NOW + 5 min
${converted_hour}= Return Twelve Hour Time ${hour}

However, the test is failing with:
KEYWORD: ${converted_hour} = UtilitiesLibrary.Return Twelve Hour Time $
{hour}
Start / End / Elapsed: 20110517 14:19:57.803 / 20110517 14:19:57.805 /
00:00:00.002
14:19:57.805 FAIL TypeError: unsupported operand type(s) for -:
'str' and 'int'

The test library just has the following code:
def return_twelve_hour_time(hour):
hour * 1
if hour >= 12:
return hour - 12
elif hour == 0:
return 12
else:
return hour

markg

unread,
May 17, 2011, 7:01:08 PM5/17/11
to robotframework-users
Found my issue. Changed this line
return hour - 12

to
return int(hour) -12

Mikko Korpela

unread,
May 18, 2011, 12:51:23 AM5/18/11
to mgib...@gmail.com, robotframework-users
Hi,

The variable that you get from robot is a string so you should parse
an integer from that before doing anything else (hour == 0 will be
false when "0" == 0).
hour * 1 does nothing.
The modulo operator '%' is quite convenient when doing the kind of
things you are doing.

Cheers,
Mikko Korpela

2011/5/18 markg <mgib...@gmail.com>:

> --
> You received this message because you are subscribed to the Google Groups "robotframework-users" group.
> To post to this group, send email to robotframe...@googlegroups.com.
> To unsubscribe from this group, send email to robotframework-u...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/robotframework-users?hl=en.
>
>

Pekka Klärck

unread,
May 18, 2011, 1:30:16 AM5/18/11
to mgib...@gmail.com, robotframework-users
2011/5/18 markg <mgib...@gmail.com>:

> Found my issue.  Changed this line
> return hour - 12
>
> to
> return int(hour) -12

As Mikko just commented, you should do this integer conversion
earlier. If you don't, comparisons like `hour >= 12` don't work as you
expect. In code you should do this instead:

def return_twelve_hour_time(hour):
hour = int(hour)


if hour >= 12:
return hour - 12
elif hour == 0:
return 12
else:
return hour


You might also want to consider using Python's time [1] or datatime
[2] modules to get the current hour automatically into your keyword.
It would make using your keyword easier as you didn't need to use `Get
Time` keyword before.

[1] http://docs.python.org/library/time.html
[2] http://docs.python.org/library/datetime.html

Cheers,
.peke
--
Agile Tester/Developer/Consultant :: http://eliga.fi
Lead Developer of Robot Framework :: http://robotframework.org

Reply all
Reply to author
Forward
0 new messages