如何计算在日期选择器日历上选择的日期之间的天数

时间:2019-08-13 18:13:51

标签: python web2py

我正在尝试计算在日期选择器上选择的日期之间的天数,并使用该值计算数据库中的 totalPrice 值。

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;")))

我希望这行在下面
Field('daysLoaned', compute=lambda r: (r['returning_date']-r['loaning_date']).days)
根据选择的日期给我一个整数值。但是相反,我遇到了这个错误
<type 'exceptions.TypeError'> unsupported operand type(s) for -: 'str' and 'str'
我不知道我在哪里做错了!

1 个答案:

答案 0 :(得分:1)

正如您的回溯所说,您的日期是字符串格式的,您不能对字符串使用减法操作数。一种选择是导入datetime并使用strptime将字符串转换为datetime对象,然后使用减法操作数获得差值。

示例:

from datetime import datetime

returning_date = datetime.strptime("2019/1/1 0:30", '%Y/%m/%d %H:%M')
loaning_date = datetime.strptime("2019/1/10 0:30", '%Y/%m/%d %H:%M')
diff = returning_date - loaning_date
print(diff)
>>> -9 days, 0:00:00

您可以通过以下方式访问日期:

print(diff.days)
>>> -9

具有类型:

print(type(diff.days))
>>> <class 'int'>

在您的代码中,这看起来像这样(取决于字符串的格式):

(datetime.strptime(r['returning_date'], '%Y/%m/%d %H:%M') - datetime.strptime(r['loaning_date'], '%Y/%m/%d %H:%M')).days