def filter_by_time_period(field, date_end=datetime.now(), total_days=1): """ Creates a string for a solr search of a date range spanning one or more days, ending on date_end. inputs: :field: The field that contains the time period being filtered on. :date_end: The latest date included in the search. :total_days: The total number of days the search should span. """ query = "{field}:[{date_end}-{total_days}DAYS TO {date_end}]" time_filter = query.format(field=field, total_days=total_days, date_end=format_date(date_end)) return time_filter
def filter_by_date(request, field=None): """ Applies date filtering. inputs: :request: A. request object including fields from the date_range form in mydashboard.html. outputs: The start and end dates for the search, and the number of days the search covers. """ requested_after_date = request.REQUEST.get('date_start', False) requested_before_date = request.REQUEST.get('date_end', False) if field is None: field = 'SavedSearch_created_on' date_end = datetime.now() # Set date range based on buttons if 'today' in request.REQUEST: date_range = filter_by_time_period(field, total_days=1) date_start = date_end - timedelta(days=1) elif 'seven_days' in request.REQUEST: date_range = filter_by_time_period(field, total_days=7) date_start = date_end - timedelta(days=7) elif 'thirty_days' in request.REQUEST: date_range = filter_by_time_period(field, total_days=30) date_start = date_end - timedelta(days=30) # Set date range based on date selection fields. else: if requested_after_date: date_start = datetime.strptime(requested_after_date, '%m/%d/%Y') else: date_start = request.REQUEST.get('date_start') if date_start: date_start = datetime.strptime(date_start, '%m/%d/%Y') else: # Default range is 30 days. date_start = datetime.now() - timedelta(days=30) if requested_before_date: date_end = datetime.strptime(requested_before_date, '%m/%d/%Y') else: date_end = request.REQUEST.get('date_end') if date_end: date_end = datetime.strptime(date_end, '%m/%d/%Y') else: # Default start date is today. date_end = datetime.now() date_range = filter_by_date_range(field=field, date_start=format_date(date_start, time_format="00:00:00Z"), date_end=format_date(date_end)) days_delta = (date_end - date_start).days return date_range, date_start, date_end, days_delta