【问题标题】:How to get minutes/hours/seconds from a django request?如何从 django 请求中获取分钟/小时/秒?
【发布时间】:2019-12-31 08:41:44
【问题描述】:

我想从请求中单独检索时间字段。但是当我尝试处理值时,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"
}

【问题讨论】:

    标签: json datetime django-models request tastypie


    【解决方案1】:

    您将其解析为 datetime 对象,例如使用 python-dateutil [PyPi]。例如:

    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

    如果这没有引发异常,start 是一个 datetime 对象。然后start。因此,您可以通过以下方式进行检查:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-13
      • 1970-01-01
      • 2020-11-21
      • 2021-06-06
      • 2022-01-15
      • 1970-01-01
      相关资源
      最近更新 更多