提问人:Cato Johnston 提问时间:6/11/2009 最后编辑:Paolo BergantinoCato Johnston 更新时间:8/25/2021 访问量:13694
获取不到一个月的所有项目
Getting all items less than a month old
问:
有没有办法在 django 中获取日期少于一个月的所有对象。
像这样:
items = Item.objects.filter(less than a month old).order_by(...)
答:
58赞
Paolo Bergantino
6/11/2009
#1
你对“月”的定义是什么?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赞
Jough Dempsey
4/21/2010
当 datetime.today() 为 3 月 1 日时,此操作失败 - 上个月是 2 月,而不是 1 月。如果你不需要它,这将正常工作(30 天前 = 上个月),但如果你确实需要知道上个月发生了什么,那么在 python (AFAIK) 中没有一个简单的方法可以解决这个问题。
1赞
Umair A.
3/24/2014
python-dateutil 中有 relatiedelta,可以为您提供确切的过去一个月。
1赞
John McCollum
6/11/2009
#2
items = Item.objects.filter(created_date__gte=aMonthAgo)
其中 aMonthAgo 将按 datetime 和 timedelta 计算。
评论
6赞
Manza
7/29/2018
如果您添加如何计算 aMonthAgo,也许会很好
3赞
Lord_Sarcastic
5/18/2020
#3
这样做:
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)
这将满足我能想到的所有情况。
评论