Home > Enterprise >  "response": "strptime() argument 1 must be str, not datetime.datetime" django da
"response": "strptime() argument 1 must be str, not datetime.datetime" django da

Time:02-20

In Django, I have written a delete method in which I am getting some requests of data from the delete API The requested data is

[
    {
      "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"
    }
]

I am deleting a row in my DB based on batch_id by using the delete method and the delete method looks like


    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)

and the row gets deleted when we run this function

My problem here is the requested data values start_time and expected_delivery_date is coming in the string format but due to some calculations in my model file, I am converting that string to a DateTime format which looks like this

the model file looks like

    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

Now the start_date and expected_delivery_date format is DateTime

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

Now this when the instance is getting the wrong response due to the wrong start_date and expected_delivery_date format the delete function is not giving the proper response

The error is

"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

How can convert again that both columns back to a string for and save that request_date and can run the delete function?

CodePudding user response:

strptime takes a string and converts it to a datetime.datetime object. You should not have passed a datetime.datetime to it.

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

If you need to convert a datetime.datetime to a string, use strftime:

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