djangodatetimedjango-modelspython-datetimedjango-timezone

How to fix RuntimeWarning: DateTimeField Question.date_time received a naive datetime?


I want to delete 60 seconds old records but I am getting this error

RuntimeWarning: DateTimeField Question.date_time received a naive datetime (2022-08-27 16:09:30.659947) while time zone support is active.

def delete(self,request):
    expiry_date_time = datetime.now() - timedelta(seconds=60)
    print('Expiry time = ',expiry_date_time)
    count = Question.objects.filter(date_time__gte = expiry_date_time).delete()
    User.objects.all().update(total_question_added=0)
    resp = {'resp' : 'All questions deleted.','Total question deleted':len(count)}
    return Response(resp)

Solution

  • use timezone.now() [Django-doc] instead, this will add the timezone to the timestamp:

    from django.http import JsonResponse
    from django.utils.timezone import now
    
    # …
    
    def delete(self, request):
        expiry_date_time = now() - timedelta(seconds=60)
        count, __ = Question.objects.filter(date_time__gte=expiry_date_time).delete()
        User.objects.update(total_question_added=0)
        return JsonResponse(
            {'resp': 'All questions deleted.', 'Total question deleted': count}
        )