How to use the iso8601.ParseError function in iso8601

To help you get started, we’ve selected a few iso8601 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github openstack / python-solumclient / solumclient / openstack / common / timeutils.py View on Github external
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))
github Uninett / nav / python / nav / web / api / v1 / views.py View on Github external
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
github dimagi / commcare-hq / corehq / form_processor / parsers / ledgers / form.py View on Github external
"""
        Goes through a parsed XML document and recursively pulls out any ledger XML blocks.
        """
        for child in node:
            if child.tag in commtrack_node_names:
                yield child
            else:
                for e in _extract_ledger_nodes_from_xml(child):
                    yield e

    for elem in _extract_ledger_nodes_from_xml(form_xml):
        report_type, ledger_json = convert_xml_to_json(elem, last_xmlns=COMMTRACK_REPORT_XMLNS)
        if ledger_json.get('@date'):
            try:
                ledger_json['@date'] = adjust_text_to_datetime(ledger_json['@date'])
            except iso8601.ParseError:
                pass
        yield _ledger_json_to_stock_report_helper(xform, report_type, ledger_json)
github jtriley / StarCluster / starcluster / utils.py View on Github external
def is_iso_time(iso):
    """
    Returns True if provided time can be parsed in iso format
    to a datetime tuple
    """
    try:
        iso_to_datetime_tuple(iso)
        return True
    except iso8601.ParseError:
        return False
github dimagi / commcare-hq / corehq / form_processor / utils / xform.py View on Github external
to force timezone processing, it can be called as follows

    >>> from corehq.apps.tzmigration.api import force_phone_timezones_should_be_processed
    >>> with force_phone_timezones_should_be_processed():
    >>>     adjust_datetimes(form_json)
    """
    process_timezones = process_timezones or phone_timezones_should_be_processed()
    # this strips the timezone like we've always done
    # todo: in the future this will convert to UTC
    if isinstance(data, six.string_types) and jsonobject.re_loose_datetime.match(data):
        try:
            parent[key] = six.text_type(json_format_datetime(
                adjust_text_to_datetime(data, process_timezones=process_timezones)
            ))
        except iso8601.ParseError:
            pass
    elif isinstance(data, dict):
        for key, value in data.items():
            adjust_datetimes(value, parent=data, key=key, process_timezones=process_timezones)
    elif isinstance(data, list):
        for i, value in enumerate(data):
            adjust_datetimes(value, parent=data, key=i, process_timezones=process_timezones)

    # return data, just for convenience in testing
    # this is the original input, modified, not a new data structure
    return data
github geocam / geocamUtilWeb / geocamUtil / TimeUtil.py View on Github external
def parseUploadTime(timeStr):
    try:
        # format used by GeoCam Mobile 2009
        return parseCsvTime(timeStr)
    except ValueError:
        pass

    try:
        # ISO 8601 format we should probably use in the future
        return iso8601.parse_date(timeStr)
    except iso8601.ParseError:
        pass

    try:
        # POSIX time stamp may be easier to produce for some clients
        posixTimeStamp = float(timeStr)
    except ValueError:
        pass
    else:
        return datetime.datetime.fromtimestamp(posixTimeStamp)

    # hm, nothing worked
    raise ValueError('could not parse datetime from %s' % timeStr)
github openstack / heat / heat / openstack / common / timeutils.py View on Github external
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)
github portfoliome / foil / foil / deserializers.py View on Github external
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
github praekeltfoundation / vumi / vumi / persist / fields.py View on Github external
def custom_validate(self, value):
        if isinstance(value, datetime):
            return

        try:
            iso8601.parse_date(value)
            return
        except iso8601.ParseError:
            pass

        raise ValidationError("Timestamp field expects a datetime or an "
                              "iso8601 formatted string.")
github ibm-watson-iot / iot-python / src / ibmiotf / codecs / jsonIotfCodec.py View on Github external
try:
        payload = json.loads(message.payload.decode("utf-8"))
    except ValueError as e:
        raise InvalidEventException("Unable to parse JSON.  payload=\"%s\" error=%s" % (message.payload, str(e)))
        
    data = None
    timestamp = None
    
    # Try to parse a timestamp
    try:
        if 'ts' in payload:
            dt = iso8601.parse_date(payload['ts'])
            timestamp = dt.astimezone(pytz.timezone('UTC'))
        else:
            timestamp = datetime.now(pytz.timezone('UTC'))
    except iso8601.ParseError as e:
        raise InvalidEventException("Unable to parse event timestamp: %s" % str(e))

    # Try to parse the data
    if 'd' in payload:
        data = payload['d']
        
        # TODO: Flatten JSON, covert into array of key/value pairs
    
    return Message(data, timestamp)