0

I am trying to delete 3 years old data in my python django db. Here is code:

from datetime import datetime
from dateutil.relativedelta import relativedelta

def db_cleanup():
    cleanup_start = datetime.utcnow().date()
    three_years_ago = cleanup_start - relativedelta(years=3)

    MyData.objects.filter(create_date__lt=three_years_ago).delete()

however I receive RuntimeWarning: DateTimeField received a naive datetime . How to do it properly?

jing
  • 1,919
  • 2
  • 20
  • 39
  • Does this answer your question? [RuntimeWarning: DateTimeField received a naive datetime](https://stackoverflow.com/questions/18622007/runtimewarning-datetimefield-received-a-naive-datetime) – May.D Jan 27 '22 at 16:51

1 Answers1

3

Use timezone.now() to create an aware datetime then reset time to midnight but keep a datetime object (not date):

from django.utils import timezone
from dateutil.relativedelta import relativedelta

def db_cleanup():
    cleanup_start = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0)
    three_years_ago = cleanup_start - relativedelta(years=3)

    MyData.objects.filter(create_date__lt=three_years_ago).delete()
Corralien
  • 109,409
  • 8
  • 28
  • 52
  • Thanks. I take it as workaround. The code gets rid of warning, but reaching UTC date by cutting off hours, ... why do I need to cut them at all? For this 3 years range I could live with just timezone.now(). I still hope to get some good solution for other places where I need e.g. 8h ago data. – jing Jan 28 '22 at 08:12
  • 1
    I cut time because you use a date and not a datetime. You can just use `three_years_ago = timezone.now() - relativedelta(years=3)` – Corralien Jan 28 '22 at 09:03