Home > Enterprise >  can't compare datetime.datetime to datetime.date django
can't compare datetime.datetime to datetime.date django

Time:10-17

I'm trying to build reservation app. I tried to find the solution but I have no idea.

I want to compare date of reservation from check_availibility with date from form. In form I've made:

check_in = forms.DateField(required=True, input_formats=["%Y-%m-%dT%H:%M", ])
check_out = forms.DateField(required=True, input_formats=["%Y-%m-%dT%H:%M", ])

import datetime

def check_availability(room, check_in, check_out): 
avail_list = [] 
booking_list = Booking.objects.filter(room=room)
for booking in booking_list:
    if booking.check_in > check_out or booking.check_out < check_in:
        avail_list.append(True)
    else:
        avail_list.append(False)
return all(avail_list) 


from hotelbooking.booking_funkctions.availibility import check_availability

class BookingView(FormView):
    form_class = AvalilabilityForm
    template_name = 'availability_form.html'

def form_valid(self, form):
    data = form.cleaned_data 
    room_list = Room.objects.filter(category=data['room_category'])
    available_rooms=[]
    for room in room_list: 
        if check_availability(room, data['check_in'], data['check_out']):
            available_rooms.append(room)

    if len(available_rooms)>0:
        room = available_rooms[0]
        booking = Booking.objects.create(
            user = self.request.user,
            room = room,
            check_in = data['check_in'],
            check_out = data['check_out']
        )
        booking.save()
        return HttpResponse(booking)
    else:
        return HttpResponse('this category of rooms are booked')

CodePudding user response:

Just call the .date() method for the datetime one:

from datetime import datetime, date

is_today_today = datetime.now().date() == date.today() # valid

print(is_today_today) # True  # (the only time that is real is the present)

CodePudding user response:

Since you're cleaning the date it should already convert the date strings to date objects, so you can do this:

def check_availability(room, check_in, check_out): 
avail_list = [] 
booking_list = Booking.objects.filter(room=room)
for booking in booking_list:
    if booking.check_in.date() > check_out.date() or booking.check_out.date() < check_in.date():
        avail_list.append(True)
    else:
        avail_list.append(False)
return all(avail_list) 
  • Related