Example #1
0
    def clean_time_end(self):
        time_end = self.cleaned_data.get("time_start").astimezone(pytz.utc)

        try:
            timestamp = utils.date_totimestamp(time_end)
        except:
            raise forms.ValidationError(
                "We couldn't parse the time_end given.\
                        Check if the format is correct")
        else:
            return timestamp
Example #2
0
def filter_by_date(
        model, date_obj, start_date, end_date, duration):
    """Creates django's filters for given date or interval

    :param model: obj where filter will be applied
    :type model: str.
    :param date_obj: database table where the requested data is
    :type date_obj: str.
    :param start_date: string start_date
    :type start_date: str.
    :param end_date: string end_date
    :type end_date: str.
    :param duration: Time interval in days.
    :type duration: str.
    :returns: dict -- A dictionary with django's query filters
    """

    dic_filter = {}
    obj = utils.get_field_instance(model, date_obj)

    if obj:
        DATE_PATTERN = "%m/%d/%Y %H:%M:%S"
        tz = tzlocal()

        start_date_filter = {}
        end_date_filter = {}

        # Apply default case, query from yesterday to now
        if not start_date:
            yesterday = timezone.now() - timezone.timedelta(1)
            start_date = yesterday.strftime(DATE_PATTERN)
        if not end_date:
            end_date = "now"

        start_date = parser.parse(start_date).replace(tzinfo=tz)

        if end_date.lower() == 'now':
            end_date = timezone.now()
        else:
            end_date = parser.parse(end_date).replace(tzinfo=tz)

        # handle duration case
        if duration:
            start_date -= utils.get_timedelta(duration)

        # handle different field instances: timestamp, datetime
        if isinstance(obj, DateTimeField):
            start_date = start_date
            end_date = end_date

        elif isinstance(obj, DecimalField):
            start_date = utils.date_totimestamp(
                start_date.astimezone(pytz.utc))
            end_date = utils.date_totimestamp(end_date.astimezone(pytz.utc))

        start_date_filter[date_obj + "__gte"] = start_date
        end_date_filter[date_obj + "__lte"] = end_date

        dic_filter.update(start_date_filter)
        dic_filter.update(end_date_filter)

    return dic_filter