Python 获取所有不到一个月的项目
有没有办法在django中获取日期不到一个月的所有对象 比如:Python 获取所有不到一个月的项目,python,django,django-views,Python,Django,Django Views,有没有办法在django中获取日期不到一个月的所有对象 比如: items = Item.objects.filter(less than a month old).order_by(...) 你对“月”的定义是什么?30天?31天?在此之后,这应该可以做到: from datetime import datetime, timedelta last_month = datetime.today() - timedelta(days=30) items = Item.objects.filte
items = Item.objects.filter(less than a month old).order_by(...)
你对“月”的定义是什么?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(...)
利用字段查找
items = Item.objects.filter(created_date__gte=aMonthAgo)
其中,aMonthAgo将由datetime和timedelta计算。执行以下操作:
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)
这将满足我能想到的所有情况。你说的“所有对象”是什么意思?你是说所有特定类型的对象吗?是的,所有类型为“Item”的对象在datetime时失败。今天()是3月1日-上个月是2月,而不是1月。如果您不需要精确,这将很好(30天前=上个月),但是如果您确实需要知道上个月发生了什么,那么在python中就没有一个简单的方法(AFAIK)。python dateutil中有relatiedelta,它可以为您提供准确的上一个月。这是一种只使用
datetime
获取上一个月的方法。如果您添加如何计算一个月,可能会更好