Home > Enterprise >  Error- unsupported operand type(s) for -: 'str' and 'datetime.timedelta' In Djan
Error- unsupported operand type(s) for -: 'str' and 'datetime.timedelta' In Djan

Time:06-20

Hi Everyone i have working on Django-framework, I am created on function where i give parameter start_date and end_date, i am trying get previous week start_date and end_date based on start_date but getting Error - unsupported operand type(s) for -: 'str' and 'datetime.timedelta', please help me out.

from datetime import datetime, timedelta, date

    def report(request):
        start_date = request.GET.get('start_date')
        print(start_date) # 2022-06-06
        end_date = request.GET.get('end_date')
        print(end_date) # 2022-06-12
        last_week_start_date=start_date - timedelta(days=7)
        last_week_end_date=last_week_start_date   timedelta(days=6)
        d_report = connection.cursor()
        d_report.execute('''select * from table where start_date=%s and end_date=%s''',[start_date,end_date])

CodePudding user response:

start_date and end_date are strings. You should convert them to a datetime object. This should be the ISO format so you can use datetime.fromisoformat()

start_date = request.GET.get('start_date')
start_date = datetime.fromisoformat(start_date)
end_date = request.GET.get('end_date')
end_date = datetime.fromisoformat(end_date)

CodePudding user response:

The problem is start_time is a str type variable. You have to convert it to datetime object first, only then you can use timedelta with that.

To convert, you can use this codebase

from datetime import datetime

datetime_object = datetime.strptime(start_time, '%Y-%m-%d')
  • Related