27

Is there a way to get all objects with a date less than a month ago in django.

Something like:

items = Item.objects.filter(less than a month old).order_by(...)
Paolo Bergantino
  • 480,997
  • 81
  • 517
  • 436
Cato Johnston
  • 44,131
  • 10
  • 39
  • 42

3 Answers3

58

What is your definition of a "month"? 30 days? 31 days? Past that, this should do it:

from datetime import datetime, timedelta
last_month = datetime.today() - timedelta(days=30)
items = Item.objects.filter(my_date__gte=last_month).order_by(...)

Takes advantange of the gte field lookup.

Paolo Bergantino
  • 480,997
  • 81
  • 517
  • 436
  • 1
    This fails when datetime.today() is March 1st - last month was February, not January. If you don't need it be exact, this will work fine (30 days ago = last month) but if you do actually need to know what happened last month, there isn't an easy way to go about it in python (AFAIK). – Jough Dempsey Apr 20 '10 at 21:35
  • 1
    there is *relatiedelta* in **python-dateutil** which can give you exact past month. – Umair A. Mar 24 '14 at 10:18
  • [Here](https://stackoverflow.com/a/9725093/209050)'s one way to get the previous month using nothing but `datetime`. – mgalgs Jan 03 '18 at 23:04
3

Do this:

from datetime import datetime, timedelta

def is_leap_year(year): 
    if year % 100 == 0:
        return year % 100 == 0

    return year % 4 == 0

def get_lapse():
    last_month = datetime.today().month
    current_year = datetime.today().year

    #is last month a month with 30 days?
    if last_month in [9, 4, 6, 11]:
        lapse = 30

    #is last month a month with 31 days?
    elif last_month in [1, 3, 5, 7, 8, 10, 12]:
        lapse = 31

    #is last month February?
    else:
        if is_leap_year(current_year):
            lapse = 29
        else:
            lapse = 30

    return lapse

last_month_filter = datetime.today() - timedelta(days=get_lapse())

items = Item.objects.filter(date_created__gte=last_month_filter)

This will cater for all cases I can think of.

Lord_Sarcastic
  • 197
  • 2
  • 10
1
items = Item.objects.filter(created_date__gte=aMonthAgo)

Where aMonthAgo would be calculated by datetime and timedelta.

John McCollum
  • 5,162
  • 4
  • 34
  • 50