有没有办法在django中获取日期不到一个月的所有对象。
类似的东西:
items = Item.objects.filter(less than a month old).order_by(...)
答案 0 :(得分:32)
您对“月份”的定义是什么? 30天? 31天?过去,应该这样做:
from datetime import datetime, timedelta
last_month = datetime.today() - timedelta(days=30)
items = Item.objects.filter(my_date__gte=last_month).order_by(...)
取得gte字段查找的优势。
答案 1 :(得分:3)
items = Item.objects.filter(created_date__gte=aMonthAgo)
其中aMonthAgo将由datetime和timedelta计算。
答案 2 :(得分:0)
执行此操作:
from datetime import datetime, timedelta
def is_leap_year(year):
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
return True
else:
return False
else:
return True
else:
return False
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)
这将满足我能想到的所有情况。