Python iso8601 模块,ParseError() 实例源码

我们从Python开源项目中,提取了以下22个代码示例,用于说明如何使用iso8601.ParseError()

项目:series-tiempo-ar-api    作者:datosgobar    | 项目源码 | 文件源码
def validate_date(self, _date, param):
        """Valida y parsea la fecha pasada.

        Args:
            _date (str): date string, ISO 8601
            param (str): Parámetro siendo parseado

        Returns:
            date con la fecha parseada

        Raises:
            ValueError: si el formato no es válido
        """

        try:
            parsed_date = iso8601.parse_date(_date)
        except iso8601.ParseError:
            self._append_error(strings.INVALID_DATE.format(param, _date))
            raise ValueError
        return parsed_date
项目:nav    作者:UNINETT    | 项目源码 | 文件源码
def get_times(request):
    """Gets start and endtime from request

    As we use no timezone in NAV, remove it from parsed timestamps
    :param request: django.http.HttpRequest
    """
    starttime = request.GET.get('starttime')
    endtime = request.GET.get('endtime')
    try:
        if starttime:
            starttime = iso8601.parse_date(starttime).replace(tzinfo=None)
        if endtime:
            endtime = iso8601.parse_date(endtime).replace(tzinfo=None)
    except iso8601.ParseError:
        raise Iso8601ParseError

    return starttime, endtime
项目:infi.clickhouse_orm    作者:Infinidat    | 项目源码 | 文件源码
def to_python(self, value, timezone_in_use):
        if isinstance(value, datetime.datetime):
            return value.astimezone(pytz.utc) if value.tzinfo else value.replace(tzinfo=pytz.utc)
        if isinstance(value, datetime.date):
            return datetime.datetime(value.year, value.month, value.day, tzinfo=pytz.utc)
        if isinstance(value, int):
            return datetime.datetime.utcfromtimestamp(value).replace(tzinfo=pytz.utc)
        if isinstance(value, string_types):
            if value == '0000-00-00 00:00:00':
                return self.class_default
            if len(value) == 10:
                try:
                    value = int(value)
                    return datetime.datetime.utcfromtimestamp(value).replace(tzinfo=pytz.utc)
                except ValueError:
                    pass
            try:
                # left the date naive in case of no tzinfo set
                dt = iso8601.parse_date(value, default_timezone=None)
            except iso8601.ParseError as e:
                raise ValueError(text_type(e))

            # convert naive to aware
            if dt.tzinfo is None or dt.tzinfo.utcoffset(dt) is None:
                dt = timezone_in_use.localize(dt)
            return dt.astimezone(pytz.utc)
        raise ValueError('Invalid value for %s - %r' % (self.__class__.__name__, value))
项目:mos-horizon    作者:Mirantis    | 项目源码 | 文件源码
def parse_isotime(timestr, default=None):
    """This duplicates oslo timeutils parse_isotime but with a
    @register.filter annotation and a silent fallback on error.
    """
    try:
        return iso8601.parse_date(timestr)
    except (iso8601.ParseError, TypeError):
        return default or ''
项目:weibo    作者:windskyer    | 项目源码 | 文件源码
def parse_isotime(timestr):
    """Parse time from ISO 8601 format"""
    try:
        return iso8601.parse_date(timestr)
    except iso8601.ParseError as e:
        raise ValueError(e.message)
    except TypeError as e:
        raise ValueError(e.message)
项目:deb-oslo.utils    作者:openstack    | 项目源码 | 文件源码
def parse_isotime(timestr):
    """Parse time from ISO 8601 format."""
    try:
        return iso8601.parse_date(timestr)
    except iso8601.ParseError as e:
        raise ValueError(six.text_type(e))
    except TypeError as e:
        raise ValueError(six.text_type(e))
项目:scriptabit    作者:DC23    | 项目源码 | 文件源码
def parse_date_utc(date, milliseconds=True):
    """Parses dates from ISO8601 or Epoch formats to a standard datetime object.

    This is particularly useful since Habitica returns dates in two
    formats::

        - iso8601 encoded strings
        - Long integer Epoch times

    Args:
        date (str): A date string in either iso8601 or Epoch format.
        milliseconds (bool): If True, then epoch times are treated as
            millisecond values, otherwise they are evaluated as seconds.

    Returns:
        datetime: The parsed date time in UTC.
    """

    parsed_date = None
    try:
        parsed_date = iso8601.parse_date(date)
    except iso8601.ParseError:
        value = int(date)
        # utcfromtimestamp expects values in seconds
        if milliseconds:
            value /= 1000
        parsed_date = datetime.utcfromtimestamp(value)

    return parsed_date.replace(tzinfo=pytz.utc)
项目:Habitica-todo    作者:eringiglio    | 项目源码 | 文件源码
def parse_date_utc(date, milliseconds=True):
    """Parses dates from ISO8601 or Epoch formats to a standard datetime object.

    This is particularly useful since Habitica returns dates in two
    formats::

        - iso8601 encoded strings
        - Long integer Epoch times

    Args:
        date (str): A date string in either iso8601 or Epoch format.
        milliseconds (bool): If True, then epoch times are treated as
            millisecond values, otherwise they are evaluated as seconds.

    Returns:
        datetime: The parsed date time in UTC.
    """

    parsed_date = None
    try:
        parsed_date = iso8601.parse_date(date)
    except iso8601.ParseError:
        value = int(date)
        # utcfromtimestamp expects values in seconds
        if milliseconds:
            value /= 1000
        parsed_date = datetime.utcfromtimestamp(value)

    return parsed_date.replace(tzinfo=pytz.utc)
项目:openregistry.api    作者:openprocurement    | 项目源码 | 文件源码
def to_native(self, value, context=None):
        if isinstance(value, datetime):
            return value
        try:
            date = parse_date(value, None)
            if not date.tzinfo:
                date = TZ.localize(date)
            return date
        except ParseError:
            raise ConversionError(self.messages['parse'].format(value))
        except OverflowError as e:
            raise ConversionError(e.message)
项目:foil    作者:portfoliome    | 项目源码 | 文件源码
def parse_iso_datetime(value):

    # Prevent iso8601 over-zealous datetime parsing
    if '-' in value and ':' in value:
        try:
            value = iso8601.parse_date(value)
        except iso8601.ParseError:
            pass

    return value
项目:catchpy    作者:nmaekawa    | 项目源码 | 文件源码
def validate_token(token_payload):
    '''check for token expiration, secret-key expiration.'''

    now = now_utc()

    # check token expiration date
    issued_at = token_payload.get('issuedAt', None)
    ttl = token_payload.get('ttl', None)
    if issued_at is None or ttl is None:
        return 'missing `issuedAt` or `ttl` in auth token'
    try:
        iat = iso8601.parse_date(issued_at)
        ttl = int(ttl)
    except iso8601.ParseError as e:
        return 'invalid `issuedAt` date format, expected iso8601. {}'.format(e)
    except ValueError:
        return 'invaild `ttl` value, expected integer'

    token_exp = iat + timedelta(seconds=ttl)
    if token_exp < now:
        return 'token has expired'

    # check for issuing at future - trying to cheat expiration?
    # taking timedrift into account
    if iat > (now + timedelta(minutes=65)):
        return 'invalid `issuedAt` in the future.'

    return None
项目:threatstack-to-s3    作者:threatstack    | 项目源码 | 文件源码
def _parse_date(date):
    '''
    Parse a date string and return a datetime object.
    '''
    try:
        return iso8601.parse_date(date)
    except iso8601.ParseError:
        raise S3ViewDateParseError('Unable to parse date: {}'.format(date))

# Service routes.
项目:strainer    作者:voidfiles    | 项目源码 | 文件源码
def datetime(value, default_tzinfo=iso8601.UTC, context=None):
    """validates that a a field is an ISO 8601 string, and converts it to a datetime object."""
    if not value:
        return

    try:
        return iso8601.parse_date(value, default_timezone=default_tzinfo)
    except iso8601.ParseError as e:
        raise ValidationException('Invalid date: %s' % (e))
项目:radar    作者:renalreg    | 项目源码 | 文件源码
def parse_date(value):
    if isinstance(value, date):
        return value
    elif isinstance(value, basestring):
        try:
            return iso8601.parse_date(value).date()
        except iso8601.ParseError:
            raise ValueError('Not a date.')
    else:
        raise ValueError('Not a date.')
项目:radar    作者:renalreg    | 项目源码 | 文件源码
def parse_datetime(value):
    if isinstance(value, datetime):
        return value
    elif isinstance(value, basestring):
        try:
            return iso8601.parse_date(value)
        except iso8601.ParseError:
            raise ValueError('Not a datetime.')
    else:
        raise ValueError('Not a datetime.')
项目:LIS-Tempest    作者:LIS    | 项目源码 | 文件源码
def parse_isotime(timestr):
    """Parse time from ISO 8601 format."""
    try:
        return iso8601.parse_date(timestr)
    except iso8601.ParseError as e:
        raise ValueError(six.text_type(e))
    except TypeError as e:
        raise ValueError(six.text_type(e))
项目:2017-rapdev-backend    作者:rit-sse    | 项目源码 | 文件源码
def parse_datetime(date_string):
    try:
        date = iso8601.parse_date(date_string)
    except iso8601.ParseError:
        return None
    return date.astimezone(pytz.utc).replace(tzinfo=None)
项目:open-wob-api    作者:openstate    | 项目源码 | 文件源码
def do_iso8601_to_str(s, format):
    try:
        return iso8601.parse_date(s).strftime(format)
    except iso8601.ParseError:
        return u''
项目:deb-subunit    作者:openstack    | 项目源码 | 文件源码
def test_parse_invalid_date():
    try:
        iso8601.parse_date(None)
    except iso8601.ParseError:
        pass
    else:
        assert 1 == 2
项目:deb-subunit    作者:openstack    | 项目源码 | 文件源码
def test_parse_invalid_date2():
    try:
        iso8601.parse_date("23")
    except iso8601.ParseError:
        pass
    else:
        assert 1 == 2
项目:toshi-reputation-service    作者:toshiapp    | 项目源码 | 文件源码
def get(self):

        reviewee = self.get_query_argument('reviewee', None)
        reviewer = self.get_query_argument('reviewer', None)
        oldest = self.get_query_argument('oldest', None)
        try:
            offset = int(self.get_query_argument('offset', 0))
            limit = int(self.get_query_argument('limit', 10))
        except ValueError:
            raise JSONHTTPError(400, body={'errors': [{'id': 'bad_arguments', 'message': 'Bad Arguments'}]})

        if reviewee is None and reviewer is None:
            raise JSONHTTPError(400, body={'errors': [{'id': 'bad arguments', 'message': 'Bad Arguments'}]})

        wheres = []
        sql_args = []

        if reviewee is not None:
            # lowercase the address
            reviewee = reviewee.lower()
            if not validate_address(reviewee):
                raise JSONHTTPError(400, body={'errors': [{'id': 'invalid_address', 'message': 'Invalid Address for `reviewee`'}]})
            wheres.append("reviewee_id = ${}".format(len(wheres) + 1))
            sql_args.append(reviewee)

        if reviewer is not None:
            # lowercase the address
            reviewer = reviewer.lower()
            if not validate_address(reviewer):
                raise JSONHTTPError(400, body={'errors': [{'id': 'invalid_address', 'message': 'Invalid Address for `reviewer`'}]})
            wheres.append("reviewer_id = ${}".format(len(wheres) + 1))
            sql_args.append(reviewer)

        if oldest is not None:
            try:
                oldest = iso8601.parse_date(oldest)
                # remove the tzinfo so asyncpg can handle them
                # fromutc adds the utc offset to the date, but doesn't remove the tzinfo
                # so the final replace is to wipe that out (which doesn't adjust anything else)
                oldest = oldest.tzinfo.fromutc(oldest).replace(tzinfo=None)
            except iso8601.ParseError:
                raise JSONHTTPError(400, body={'errors': [{'id': 'invalid_date', 'message': 'Invalid date for `oldest`'}]})
            wheres.append("updated >= ${}".format(len(wheres) + 1))
            sql_args.append(oldest)

        cnt_sql = "SELECT COUNT(*) FROM reviews WHERE {}".format(" AND ".join(wheres))
        sql = "SELECT * FROM reviews WHERE {} ORDER BY updated DESC OFFSET ${} LIMIT ${}".format(
            " AND ".join(wheres), len(wheres) + 1, len(wheres) + 2)

        async with self.db:
            reviews = await self.db.fetch(sql, *sql_args + [offset, limit])
            stats = await self.db.fetchrow(cnt_sql, *sql_args)

        self.write({
            "query": self.request.query,
            "total": stats['count'],
            "reviews": [render_review(r) for r in reviews],
            "offset": offset,
            "limit": limit
        })
项目:suite    作者:Staffjoy    | 项目源码 | 文件源码
def get(self, org_id, location_id, role_id):
        parser = reqparse.RequestParser()
        parser.add_argument("start", type=str, required=True)
        parser.add_argument("stop", type=str, required=True)
        parameters = parser.parse_args()

        allow_past = g.current_user.is_sudo(
        ) or g.current_user.is_org_admin_or_location_manager(org_id,
                                                             location_id)

        # start time
        try:
            start = iso8601.parse_date(parameters.get("start"))
        except iso8601.ParseError:
            return {
                "message": "Start time needs to be in ISO 8601 format"
            }, 400
        else:
            start = (start + start.utcoffset()).replace(tzinfo=None)

        # stop time
        try:
            stop = iso8601.parse_date(parameters.get("stop"))
        except iso8601.ParseError:
            return {"message": "Stop time needs to be in ISO 8601 format"}, 400
        else:
            stop = (stop + stop.utcoffset()).replace(tzinfo=None)

        # stop can't be before start
        if start >= stop:
            return {"message": "Stop time must be after start time"}, 400

        # shifts are limited to 23 hours in length
        if int((stop - start).total_seconds()) > MAX_SHIFT_LENGTH:
            return {
                "message":
                "Shifts cannot be more than %s hours long" %
                (MAX_SHIFT_LENGTH / SECONDS_PER_HOUR)
            }, 400

        # create a shift object - do NOT add to db session though
        shift = Shift2(role_id=role_id, start=start, stop=stop)

        within_caps, exceeds_caps = shift.get_all_eligible_users(
            allow_past=allow_past)
        marshal_within = [marshal(user, user_fields) for user in within_caps]
        marshal_exceeds = [marshal(user, user_fields) for user in exceeds_caps]

        for user in marshal_within:
            user["within_caps"] = True

        for user in marshal_exceeds:
            user["within_caps"] = False

        return {API_ENVELOPE: marshal_within + marshal_exceeds}