首先是当前时间的确定,对于年月日,orm模型都有对应的方法直接查询,周是没有方法直接查询的,我是没有找到这个方法,只能间接的查询
1
2
3
|
now_time = datetime.datetime.now() # 如果数据库保存的是UTC时间,程序不会蹦但是会提示你这不是本地时间
now_time_utc = datetime.datetime.utcnow()
|
查询本周产生的数据
1
2
3
4
5
6
|
# 当前天 显示当前日期是本周第几天 day_num = cur_time.isoweekday()
# 计算当前日期所在周一 monday = (cur_time - datetime.timedelta(days = day_num))
# 查询一周内的数据 all_datas = YourModel.objects. filter (time__range = (now_time, monday))
|
查询本月的数据
1
|
all_datas = YourModel.objects. filter (time__month = now_time.month)
|
查询本年的数据
1
|
all_datas = YourModel.objects. filter (time__year = now_time.year)
|
1、gt:大于某个时间
now = datetime.datetime.now()
#前一天
start = now – datetime.timedelta(hours=23, minutes=59, seconds=59)
a=yourobject.objects .filter(youdatetimcolumn__gt=start)
2、gte:大于等于某个时间:
a=yourobject.objects .filter(youdatetimcolumn__gte=start)
3、lt:小于
a=yourobject.objects .filter(youdatetimcolumn__lt=start)
4、lte:小于等于
a=yourobject.objects .filter(youdatetimcolumn__lte=start)
5、range:查询时间段
start_date = datetime.date(2005, 1, 1)
end_date = datetime.date(2005, 3, 31)
Entry.objects.filter(pub_date__range=(start_date, end_date))
6、year:查询某年
Entry.objects.filter(pub_date__year=2005)
7、month:查询某月
Entry.objects.filter(pub_date__month=12)
8、day:某天
Entry.objects.filter(pub_date__day=3)
9、week_day:星期几
Entry.objects.filter(pub_date__week_day=2)
10、获取今天的日期,日期格式为yyyy-MM-dd
from django.utils.timezone import now, timedelta
date = now().date() + timedelta(days=-1) #昨天
date = now().date() + timedelta(days=0) #今天
date = now().date() + timedelta(days=1) #明天