A calculation gives <type 'exceptions.TypeError'> unsupported operand type(s) for -: 'str' and 'str'

30 views
Skip to first unread message

mostwanted

unread,
Aug 13, 2019, 7:47:45 AM8/13/19
to web2py-users
I am trying to calculate the number of days and use that value in another calculation in my database.
I used this method below which used to to work perfectly but todays its giving me an error
db.define_table('invoice',
               
Field('loaning_date', 'date', label=SPAN('Date Loaned', _style="font-weight: bold;"), requires=IS_NOT_EMPTY()),
               
Field('returning_date', 'date', label=SPAN('Date Returned', _style="font-weight: bold;"), requires=IS_NOT_EMPTY()),
                              #Number of days calculation
               
Field('daysLoaned', compute=lambda r: (r['returning_date']-r['loaning_date']).days),
               
Field('price', 'float', label=SPAN('Price', _style="font-weight: bold;"), requires=IS_MATCH('[0-9]+', error_message=T('Enter Money in Proper Figures'))),
               
Field('totalPrice', compute=lambda r: float(r['price'])* int(r['daysLoaned']), label=SPAN('Total Price', _style="font-weight: bold;")))

Why am i getting this error? How do i rectify it, maybe i am missing something!

Regards;

Mostwanted

villas

unread,
Aug 13, 2019, 8:26:17 AM8/13/19
to web2py-users
Check in DB what kind of field is 'daysLoaned'.  Maybe it is defined as a Str field?
Try:  Field('daysLoaned', compute=lambda r: str(r['returning_date']-r['loaning_date']).days)
Just an idea...


mostwanted

unread,
Aug 13, 2019, 1:12:07 PM8/13/19
to web2py-users
My understanding of the error is that i can not subtract strings, which is true, but these fiends on which i am performing subtraction are dates and i was trying to pick their days when i put them into ().days  so they wont be treated as strings because they are date fields, i cant figure out why it is not working!

Dave S

unread,
Aug 13, 2019, 5:35:55 PM8/13/19
to web2py-users


On Tuesday, August 13, 2019 at 10:12:07 AM UTC-7, mostwanted wrote:
My understanding of the error is that i can not subtract strings, which is true, but these fiends on which i am performing subtraction are dates and i was trying to pick their days when i put them into ().days  so they wont be treated as strings because they are date fields, i cant figure out why it is not working!

They are date fields.  Subtract them directly to get a datetime.timedelta object:
    compute = lambda r: {tdelta = r.returning_date - r.loaning_date; return tdelta.days}
See Sec 8.1 (8.1.2, especially) of the Python standard Library

/dps

mostwanted

unread,
Aug 14, 2019, 2:43:27 AM8/14/19
to web2py-users
Someone suggested that i try this:
from datetime import datetime
(datetime.strptime(r['returning_date'], '%Y/%m/%d %H:%M') - datetime.strptime(r['loaning_date'], '%Y/%m/%d %H:%M')).days
and it solved the problem

Regards;
Mostwanted
Reply all
Reply to author
Forward
0 new messages