如何从 Django 请求中获取 minutes/hours/seconds?
How to get minutes/hours/seconds from a django request?
我想从请求中单独检索时间字段。但是当我尝试处理值时,HttpResponse 给出了 406 状态代码。
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)
这是我发送的 json 对象:
{
"vehic__id": 1,
"spot__id": 1,
"start": "2018-03-29T23:00:00.999Z",
"end" : "2018-03-30T23:00:30.000Z"
}
您将其解析为 datetime
对象,例如 python-dateutil
[PyPi]。例如:
from dateutil.parser import parse as dtparse
try:
start = <b>dtparse(</b>body_as_json.get('start')<b>)</b>
except (ValueError, TypeError):
# ... (invalid date, or not a string)
pass
如果这没有引发异常,start
是一个 datetime
对象。然后是start
。所以你可以检查这个:
if not start.minute % 15:
# minute is 0, 15, 30, or 45
pass
else:
# not the case
pass
我想从请求中单独检索时间字段。但是当我尝试处理值时,HttpResponse 给出了 406 状态代码。
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)
这是我发送的 json 对象:
{
"vehic__id": 1,
"spot__id": 1,
"start": "2018-03-29T23:00:00.999Z",
"end" : "2018-03-30T23:00:30.000Z"
}
您将其解析为 datetime
对象,例如 python-dateutil
[PyPi]。例如:
from dateutil.parser import parse as dtparse
try:
start = <b>dtparse(</b>body_as_json.get('start')<b>)</b>
except (ValueError, TypeError):
# ... (invalid date, or not a string)
pass
如果这没有引发异常,start
是一个 datetime
对象。然后是start
。所以你可以检查这个:
if not start.minute % 15:
# minute is 0, 15, 30, or 45
pass
else:
# not the case
pass