"response": "strptime() argument 1 must be str, not datetime.datetime" django 日期时间格式问题

"response": "strptime() argument 1 must be str, not datetime.datetime" django datetime format problem

在 Django 中,我编写了一个删除方法,在该方法中我从删除中获取了一些数据请求 API 请求的数据是

[
    {
      "acerage": 1,
      "batch_health": null,
      "actual_produce": null,
      "actual_yield_per_acre": null,
      "batch_id": 2583,
      "batch_status": "running",
      "commodity_id": 6,
      "commodity_variety_id": 20,
      "current_gdd": null,
      "current_pdd": null,
      "expected_delivery_date": "2022-02-15T18:30:00.000Z",
      "expected_produce": null,
      "farm_id": "1806",
      "historic_gdd": null,
      "historic_pdd": null,
      "historical_yield_per_acre": null,
      "sop_adherence": null,
      "stage": "germination",
      "start_date": "2022-02-06T18:30:00.000Z"
    }
]

我正在使用 delete 方法删除基于 batch_id 的数据库中的一行 并且删除方法看起来像


    def destroy(self, request, *args, **kwargs):
        """
            This function is used to destroy batch object
        """
        try:
            instance = self.get_object()
            instance.batch_status = 'aborted'
            instance.save()
            solr_delta_import()
        except Exception as e:
            return Response({"response": str(e)}, status=status.HTTP_400_BAD_REQUEST)
        return Response({"response": "deleted successfully"}, status=status.HTTP_200_OK)

当我们运行这个函数

时,该行被删除

我的问题是请求的数据值 start_time 和 expected_delivery_date 以字符串格式出现 但是由于模型文件中的一些计算,我将该字符串转换为 DateTime 格式,如下所示

模型文件看起来像

    def update_batch_median_health(self):
        if self.start_date and self.expected_delivery_date:
            if self.id:
                start_date = datetime.strptime(self.start_date, '%Y-%m-%dT%H:%M:%SZ')
                expected_delivery_date = datetime.strptime(self.expected_delivery_date, '%Y-%m-%dT%H:%M:%SZ')
            else:
                start_date = datetime.combine(self.start_date, datetime.min.time())
                expected_delivery_date = datetime.combine(self.expected_delivery_date, datetime.min.time())
            end_date = min([expected_delivery_date, datetime.today()]) - relativedelta(hours=5, minutes=30)
            hours_diff = int((((end_date - start_date).total_seconds()) / 3600 / 2))
            median_date = start_date + relativedelta(hours=hours_diff)
            
            try:
                median_crop_health = self.history.as_of(median_date).crop_health
            except:
                median_crop_health = self.batch_health
            return median_crop_health
        else:
            return None

    def update_batch_name(self):
        batch_name = "({}) {}".format(self.id, self.commodity_name)
        if self.start_date:
            if self.id:
                start_date = self.start_date.split("T")
                batch_name += " | {}".format(start_date[0])
            else:
                batch_name += " | {}".format(self.start_date.strftime('%Y-%m-%d'))
        return batch_name

现在 start_date 和 expected_delivery_date 格式是 DateTime

start_date = 2022-02-06 18:30:00+00:00
expected_delivery_date = 2022-02-15 18:30:00+00:00

现在,当实例由于错误的 start_date 和 expected_delivery_date 格式而得到错误的响应时,删除功能没有给出正确的响应

错误是

"response": "strptime() argument 1 must be str, not datetime.datetime"
}

Bad Request: /api/v1/batch/2583/
[19/Feb/2022 08:01:49] "DELETE /api/v1/batch/2583/ HTTP/1.1" 400 71

如何再次将这两列转换回字符串并保存 request_date 并且可以 运行 删除功能?

strptime 获取一个字符串并将其转换为 datetime.datetime 对象。您不应该向它传递 datetime.datetime

datetime.datetime.strptime("2021-02-19", "%Y-%m-%d")
datetime.datetime(2021, 2, 19, 0, 0)

如果需要将 datetime.datetime 转换为字符串,请使用 strftime:

mytime = datetime.datetime(2022, 2, 19, 14, 23, 51)
mytime.strftime('%Y-%m-%dT%H:%M:%SZ')
'2022-02-19T14:23:51Z'