now = datetime.datetime.now()
# 打印day_start之后得到的是 2019-04-16 19:16:26.150070 表示现在的前24个小时
day_start = now - datetime.timedelta(hours=23, minutes=59, seconds=59)
# 然后我看源码 还有周,日 毫秒,微秒等等
class timedelta(SupportsAbs[timedelta]):
min: ClassVar[timedelta]
max: ClassVar[timedelta]
resolution: ClassVar[timedelta]
if sys.version_info >= (3, 6):
def __init__(self, days: float = ..., seconds: float = ..., microseconds: float = ...,
milliseconds: float = ..., minutes: float = ..., hours: float = ...,
weeks: float = ..., *, fold: int = ...) -> None: ...
else:
def __init__(self, days: float = ..., seconds: float = ..., microseconds: float = ...,
milliseconds: float = ..., minutes: float = ..., hours: float = ...,
weeks: float = ...) -> None: ...
# 分别拿到 周 月 是得到现在的时间之前的一周和一个月 然后在queryset中 使用addtime__gte 小于等于的时间格式去过滤,就可以得到所有这个时间段的数据
week_start = now - datetime.timedelta(weeks=1)
month_start = now - datetime.timedelta(days=30)
1、lt:小于
queryset=yourobject.objects .filter(时间字段名称__lt=start)
2、lte:小于等于
queryset=yourobject.objects .filter(时间字段名称__lte=start)
3、gt:大于某个时间
now = datetime.datetime.now()
#前一天
start = now – datetime.timedelta(hours=23, minutes=59, seconds=59)
start = now+datetime.timedelta(day=-1)
queryset=MemberRole.objects .filter(时间字段名称__gt=start)
4、gte:大于等于某个时间:
queryset=MemberRole.objects .filter(时间字段名称__gte=start)
5、year:查询某年
MemberRole.objects.filter(时间字段名称__year=2005)
6、month:查询某月
MemberRole.objects.filter(时间字段名称__month=12)
7、day:某天
MemberRole.objects.filter(时间字段名称__day=3)
8、week_day:星期几
MemberRole.objects.filter(时间字段名称__week_day=2)
9、range:查询时间段
start_date = datetime.date(2005, 1, 1)
end_date = datetime.date(2005, 3, 31)
10、获取上个月第一天和最后一天
import datetime
fist = datetime.date(datetime.date.today().year,datetime.date.today().month-1,1)
last = datetime.date(datetime.date.today().year,datetime.date.today().month,1)-datetime.timedelta(1)