Search code examples
jsondatetimedjango-modelsrequesttastypie

How to get minutes/hours/seconds from a django request?


I wanna retrieve time fields separately from a request. But when I try to process values, HttpResponse gives 406 status code.

def ReservationActions(request):
  if(request.method == 'POST'):
    body_as_json = json.loads(request.body)
    try:
      veh = Vehicles.objects.get(id = body_as_json['vehic__id'])
      sp = ParkingSpots.objects.get(id = body_as_json['spot__id'])
      reserve = Reservations(vehic = veh, spot = sp, start_date = body_as_json.get('start'), end_date = body_as_json.get('end'))
      if(reserve.start_date.datetime.minute % 15 is not 0): #this is where it goes to "except" part
        return HttpResponse(status=306)
      reserve.save()
      # Return a "created" (201) status code.
      return HttpResponse(status=201)
    except:
      # Return a "not acceptable" (406) status code.
      return HttpResponse(status=406)

this is the json object I send:

{
  "vehic__id": 1,
  "spot__id": 1,
  "start": "2018-03-29T23:00:00.999Z",
  "end" : "2018-03-30T23:00:30.000Z"
}

Solution

  • You parse it to a datetime object, for example with the python-dateutil [PyPi]. For example with:

    from dateutil.parser import parse as dtparse
    
    try:
    start = dtparse(body_as_json.get('start'))
    except (ValueError, TypeError):
        # ... (invalid date, or not a string)
        pass

    In case this does not raise an exception, start is a datetime object. Then the start. So you can check this with:

    if not start.minute % 15:
        # minute is 0, 15, 30, or 45
        pass
    else:
        # not the case
        pass