Python django.utils.dateparse.parse_time() Examples

The following are 13 code examples of django.utils.dateparse.parse_time(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.utils.dateparse , or try the search function .
Example #1
Source File: base.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def convert_values(self, value, field):
        """SQLite returns floats when it should be returning decimals,
        and gets dates and datetimes wrong.
        For consistency with other backends, coerce when required.
        """
        internal_type = field.get_internal_type()
        if internal_type == 'DecimalField':
            return util.typecast_decimal(field.format_number(value))
        elif internal_type and internal_type.endswith('IntegerField') or internal_type == 'AutoField':
            return int(value)
        elif internal_type == 'DateField':
            return parse_date(value)
        elif internal_type == 'DateTimeField':
            return parse_datetime_with_timezone_support(value)
        elif internal_type == 'TimeField':
            return parse_time(value)

        # No field, or the field isn't known to be a decimal or integer
        return value 
Example #2
Source File: __init__.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def to_python(self, value):
        if value is None:
            return None
        if isinstance(value, datetime.time):
            return value
        if isinstance(value, datetime.datetime):
            # Not usually a good idea to pass in a datetime here (it loses
            # information), but this can be a side-effect of interacting with a
            # database backend (e.g. Oracle), so we'll be accommodating.
            return value.time()

        try:
            parsed = parse_time(value)
            if parsed is not None:
                return parsed
        except ValueError:
            msg = self.error_messages['invalid_time'] % value
            raise exceptions.ValidationError(msg)

        msg = self.error_messages['invalid'] % value
        raise exceptions.ValidationError(msg) 
Example #3
Source File: operations.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def convert_timefield_value(self, value, expression, connection, context):
        if value is not None and not isinstance(value, datetime.time):
            value = parse_time(value)
        return value 
Example #4
Source File: __init__.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def to_python(self, value):
        if value is None:
            return None
        if isinstance(value, datetime.time):
            return value
        if isinstance(value, datetime.datetime):
            # Not usually a good idea to pass in a datetime here (it loses
            # information), but this can be a side-effect of interacting with a
            # database backend (e.g. Oracle), so we'll be accommodating.
            return value.time()

        try:
            parsed = parse_time(value)
            if parsed is not None:
                return parsed
        except ValueError:
            raise exceptions.ValidationError(
                self.error_messages['invalid_time'],
                code='invalid_time',
                params={'value': value},
            )

        raise exceptions.ValidationError(
            self.error_messages['invalid'],
            code='invalid',
            params={'value': value},
        ) 
Example #5
Source File: harrastushaku.py    From linkedevents with MIT License 5 votes vote down vote up
def build_sub_event_time_ranges(self, start_date, end_date, time_tables):
        sub_event_time_ranges = []

        for time_table in time_tables:
            current_date = start_date
            weekday = int(time_table.get('weekday'))
            start_time = parse_time(time_table.get('starttime'))
            end_time = parse_time(time_table.get('endtime'))
            repetition = int(time_table.get('repetition'))
            if repetition == 0:
                repetition = 7  # assume repetition 0 and 7 mean the same thing

            if not (weekday and repetition) or start_time >= end_time:
                continue

            while current_date.isoweekday() != weekday:
                current_date += timedelta(days=1)

            while current_date <= end_date:
                sub_event_time_ranges.append(SubEventTimeRange(
                    datetime.combine(current_date, start_time).astimezone(TIMEZONE),
                    datetime.combine(current_date, end_time).astimezone(TIMEZONE),
                ))
                current_date += timedelta(days=repetition)

        return sub_event_time_ranges 
Example #6
Source File: operations.py    From bioforum with MIT License 5 votes vote down vote up
def convert_timefield_value(self, value, expression, connection):
        if value is not None:
            if not isinstance(value, datetime.time):
                value = parse_time(value)
        return value 
Example #7
Source File: operations.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def convert_timefield_value(self, value, expression, connection):
        if value is not None:
            if not isinstance(value, datetime.time):
                value = parse_time(value)
        return value 
Example #8
Source File: field_block.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def to_python(self, value):
        if value is None or isinstance(value, datetime.time):
            return value
        else:
            return parse_time(value) 
Example #9
Source File: operations.py    From python with Apache License 2.0 5 votes vote down vote up
def convert_timefield_value(self, value, expression, connection, context):
        if value is not None:
            if not isinstance(value, datetime.time):
                value = parse_time(value)
        return value 
Example #10
Source File: operations.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def convert_timefield_value(self, value, expression, connection, context):
        if value is not None:
            if not isinstance(value, datetime.time):
                value = parse_time(value)
        return value 
Example #11
Source File: operations.py    From python2017 with MIT License 5 votes vote down vote up
def convert_timefield_value(self, value, expression, connection, context):
        if value is not None:
            if not isinstance(value, datetime.time):
                value = parse_time(value)
        return value 
Example #12
Source File: fields.py    From esdc-ce with Apache License 2.0 5 votes vote down vote up
def from_native(self, value):
        if value in validators.EMPTY_VALUES:
            return None

        if isinstance(value, datetime.time):
            return value

        for fmt in self.input_formats:
            if fmt.lower() == ISO_8601:
                try:
                    parsed = parse_time(value)
                except (ValueError, TypeError):
                    pass
                else:
                    if parsed is not None:
                        return parsed
            else:
                try:
                    parsed = datetime.datetime.strptime(value, fmt)
                except (ValueError, TypeError):
                    pass
                else:
                    return parsed.time()

        msg = self.error_messages['invalid'] % readable_time_formats(self.input_formats)

        raise ValidationError(msg) 
Example #13
Source File: query_parsing.py    From urbanfootprint with GNU General Public License v3.0 4 votes vote down vote up
def parse_simple_token(token, manager, related_models, left=False, sibling_token=None):
    """
        Parse the simple token dict.
        :param token: a dict with 'tokenType'=='PROPERTY'|'NUMBER'|'STRING'
            and 'tokenValue'==a value of the corresponding type.
        :param manager: The django model manager
        :param related_models: Related models joined to the manager model
        :param left: Default False. If set then the token is an assignee and shouldn't be wrapped in
        an F() expression if it's a property
        :param sibling_token: the left side token if we are evaluating a right side token (left=False)
    """
    if token['tokenType'] == 'PROPERTY':
        # Resolve the field path in case it's relative to a joined related_model
        field_path = resolve_field_path_via_geographies('__'.join(token['tokenValue'].split('.')), manager, related_models)
        # Wrap in an F() expression if field is a right-side argument (the thing being assigned)
        return field_path if left else F(field_path)
    elif token['tokenType'] == 'NUMBER':
        return float(token['tokenValue'])
    elif token['tokenType'] in ['STRING', 'null', 'undefined']:
        if token['tokenType'] in ['null', 'undefined']:
            # Accept the 'null' or 'undefined' tokenType to mean None
            value = None
        else:
            value = token['tokenValue']

        if sibling_token and sibling_token.get('tokenType', None) == 'PROPERTY':
            # If we are evaluating a right-side token, inspect the sibling_token (the left-side token)
            # to find out what type the property is. This only matters for Dates and Times
            # where we need to modify the resolved right-side value to be have a time zone
            # if one isn't specified

            # Resolve the possibly chained property
            field_path = resolve_field_path_via_geographies('__'.join(sibling_token['tokenValue'].split('.')), manager, related_models)
            field = resolve_field_of_path(manager, field_path)
            if not field:
                return

            parser_lookup = {DateTimeField: parse_datetime, DateField: parse_date, TimeField: parse_time}
            if isinstance(field, (DateTimeField, DateField, TimeField)):
                date_time = parser_lookup[field.__class__](value)
                if not date_time and isinstance(field, DateTimeField):
                    # Accept dates without times for datetimes
                    date_time = timezone.utc.localize(datetime.combine(parser_lookup[DateField](value), datetime.min.time()))
                if isinstance(field, (DateTimeField, TimeField)) and not date_time.tzinfo:
                    # Default the timezone to UTC
                    return date_time.replace(tzinfo=timezone.utc)
                return date_time
        return value

    # TODO handle booleans and other types
    return token['tokenType']