Exception was: unsupported operand type(s) for -: 'str' and 'datetime.timedelta'
Asked Answered
P

2

5

I am new with python and I am making a system that deals with request.GET method... when i pass a date to the system, if it is exist then it will look for the database and show data according to that date and other dates, else it will display a date with other date... here is my code :

from django.utils.xmlutils import SimplerXMLGenerator
from piston.handler import BaseHandler
from booking.models import *
from django.db.models import *
from piston.utils import rc, require_mime, require_extended, validate
import datetime

class BookingHandler(BaseHandler):
    allowed_method = ('GET', 'POST', 'PUT', 'DELETE')
    fields = ('id', 'date_select', 'product_name', 'quantity', 'price','totalcost', 'first_name', 'last_name', 'contact', 'product')
    model = Booking
    #for product availability
    def read(self, request, id, date_select):
        if not self.has_model():
            return rc.NOT_IMPLEMENTED
        try:   
            prod = Product.objects.get(id=id)
            merge = []
            checkDateExist = Booking.objects.filter(date_select=date_select)
            if checkDateExist.exists():
                entered_date = Booking.objects.values('date_select').distinct('date_select').filter(date_select=date_select)[0]['date_select']
            else:             
                enteredTemp_date = datetime.datetime.strptime(date_select, '%Y-%m-%d')
                entered_date = datetime.datetime.strftime(enteredTemp_date,'%Y-%m-%d')


            delta = datetime.timedelta(days=3)
            target_date = entered_date - delta
            day = 1
            for x in range(0,5):
                delta = datetime.timedelta(days=x+day)
                new_date = target_date + delta
                maximumProdQuantity = prod.quantity
                quantityReserve = Booking.objects.filter(date_select=new_date, product=prod).aggregate(Sum('quantity'))['quantity__sum']
                if quantityReserve == None:
                    quantityReserve = 0

                data1 = {'maximum_guest': maximumProdQuantity, 'avialable': quantityReserve, 'date': new_date}
                merge.append(data1)    

            return merge       
        except self.model.DoesNotExist:
            return rc.NOT_HERE 

and i got this error :

Piston/0.3dev (Django 1.3.1) crash report:

Method signature does not match.

Signature should be: id, date_select

Exception was: unsupported operand type(s) for -: 'str' and 'datetime.timedelta'

i think in my else statement the entered_date become a string, i do this line entered_date = datetime.datetime.strftime(enteredTemp_date,'%Y-%m-%d') so that the date format will be not 2011-12-01 00:00:00 i just only need 2011-12-01. my question is how can i get 2011-12-01 that is datetime format not a string? can anyone can give a hint or an idea about my case? thanks

Porty answered 3/12, 2011 at 6:33 Comment(0)
I
8

strftime returns a formatted string. If you want to discard time portion of datetime object, use datetime.date:

entered_date = datetime.datetime.strptime(date_select, '%Y-%m-%d')
entered_date = entered_date.date()
Intercept answered 3/12, 2011 at 6:42 Comment(0)
H
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''hi, your need to transfor the stirng to the date formation.
use this :
'''


import datetime
import time
from datetime import timedelta

today = datetime.date.today()
print(today)


# 0r 
from datetime import date
today1 = date.today()
print(today1)


tomorrow = today - datetime.timedelta(days=7)
print(str(tomorrow))

# it is ok, because the today is date formation


#but the following it is not ok

event_day= "2021-05-18"
tomorrow = event_day - datetime.timedelta(days=7)

# you should do this:
text='2021-5-10'
x=datetime.datetime.strptime(text, '%Y-%m-%d').date()

print(x) # it's ok


# hope this help you!
Horn answered 26/5, 2021 at 8:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.