當前位置: 首頁>>代碼示例>>Python>>正文


Python isodate.parse_datetime方法代碼示例

本文整理匯總了Python中isodate.parse_datetime方法的典型用法代碼示例。如果您正苦於以下問題:Python isodate.parse_datetime方法的具體用法?Python isodate.parse_datetime怎麽用?Python isodate.parse_datetime使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在isodate的用法示例。


在下文中一共展示了isodate.parse_datetime方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _insert_post

# 需要導入模塊: import isodate [as 別名]
# 或者: from isodate import parse_datetime [as 別名]
def _insert_post(url, user, data, session):
    try:
        date_time = parse_datetime(data["created_time"])
    except ISO8601Error:
        date_time = datetime.now()
    if not data.get("message") or len(data.get("message")) > 160:
        caption = ""
    else:
        caption = data.get("message").strip()
    facebook_id = data["id"]
    likes_count = data["reactions"]["summary"]["total_count"]
    permalink_url = data["permalink_url"]
    new_link = _insert_link(url, session)
    if not new_link:
        new_link = session.query(Link).filter(Link.url == url).first()
        new_post = UserPosts(
            user, new_link, date_time, caption, facebook_id, permalink_url
        )
        new_post.likes_count = likes_count
        session.add(new_post)
        return None
    new_post = UserPosts(user, new_link, date_time, caption, facebook_id, permalink_url)
    new_post.likes_count = likes_count
    session.add(new_post)
    return new_link 
開發者ID:lttkgp,項目名稱:C-3PO,代碼行數:27,代碼來源:metadata.py

示例2: extract_utc_timestamp_from_log_line

# 需要導入模塊: import isodate [as 別名]
# 或者: from isodate import parse_datetime [as 別名]
def extract_utc_timestamp_from_log_line(line: str) -> datetime.datetime:
    """
    Extracts the timestamp from a log line of the format "<timestamp> <other data>" and returns a UTC datetime object
    or None if it could not parse the line
    """
    # Extract ISO 8601 date per http://www.pelagodesign.com/blog/2009/05/20/iso-8601-date-validation-that-doesnt-suck/
    iso_re = (
        r"^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|"
        r"(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24\:?00)([\.,]\d+"
        r"(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)? "
    )

    tokens = re.match(iso_re, line)

    if not tokens:
        # Could not parse line
        return None
    timestamp = tokens.group(0).strip()
    dt = isodate.parse_datetime(timestamp)
    utc_timestamp = datetime_convert_timezone(dt, dt.tzinfo, tz.tzutc())
    return utc_timestamp 
開發者ID:Yelp,項目名稱:paasta,代碼行數:23,代碼來源:logs.py

示例3: marathon_log_line_passes_filter

# 需要導入模塊: import isodate [as 別名]
# 或者: from isodate import parse_datetime [as 別名]
def marathon_log_line_passes_filter(
    line: str,
    levels: Sequence[str],
    service: str,
    components: Iterable[str],
    clusters: Sequence[str],
    instances: Iterable[str],
    start_time: datetime.datetime = None,
    end_time: datetime.datetime = None,
) -> bool:
    """Given a (JSON-formatted) log line where the message is a Marathon log line,
    return True if the line should be displayed given the provided service; return False
    otherwise."""
    try:
        parsed_line = json.loads(line)
    except ValueError:
        log.debug("Trouble parsing line as json. Skipping. Line: %r" % line)
        return False

    timestamp = isodate.parse_datetime(parsed_line.get("timestamp"))
    if not check_timestamp_in_range(timestamp, start_time, end_time):
        return False
    return format_job_id(service, "") in parsed_line.get("message", "") 
開發者ID:Yelp,項目名稱:paasta,代碼行數:25,代碼來源:logs.py

示例4: _parse_determine_date_datetime

# 需要導入模塊: import isodate [as 別名]
# 或者: from isodate import parse_datetime [as 別名]
def _parse_determine_date_datetime(s: str) -> Union[datetime.datetime,
                                                    datetime.date]:
    """Parse function parses a date, if time is included it parses as a
    datetime.
    """
    if sys.version_info >= (3, 7):
        # Check if the date includes time.
        if 'T' in s:
            return datetime.datetime.fromisoformat(s)
        else:
            return datetime.date.fromisoformat(s)
    else:
        # Check if the date includes time.
        if 'T' in s:
            return isodate.parse_datetime(s)
        else:
            return isodate.parse_date(s)


# Test if lists/tuples have contain matching items 
開發者ID:micahcochran,項目名稱:scrape-schema-recipe,代碼行數:22,代碼來源:scrape.py

示例5: test_datetime_rfc

# 需要導入模塊: import isodate [as 別名]
# 或者: from isodate import parse_datetime [as 別名]
def test_datetime_rfc(self):
        client = AutoRestRFC1123DateTimeTestService(base_url="http://localhost:3000")

        assert await client.datetimerfc1123.get_null() is None

        with pytest.raises(DeserializationError):
            await client.datetimerfc1123.get_invalid()

        with pytest.raises(DeserializationError):
            await client.datetimerfc1123.get_underflow()

        with pytest.raises(DeserializationError):
            await client.datetimerfc1123.get_overflow()

        await client.datetimerfc1123.get_utc_lowercase_max_date_time()
        await client.datetimerfc1123.get_utc_uppercase_max_date_time()
        await client.datetimerfc1123.get_utc_min_date_time()

        max_date = isodate.parse_datetime("9999-12-31T23:59:59.999999Z")
        await client.datetimerfc1123.put_utc_max_date_time(max_date)

        min_date = isodate.parse_datetime("0001-01-01T00:00:00Z")
        await client.datetimerfc1123.put_utc_min_date_time(min_date) 
開發者ID:Azure,項目名稱:autorest.python,代碼行數:25,代碼來源:test_datetime_rfc.py

示例6: test_datetime_rfc

# 需要導入模塊: import isodate [as 別名]
# 或者: from isodate import parse_datetime [as 別名]
def test_datetime_rfc(self):
        client = AutoRestRFC1123DateTimeTestService(base_url="http://localhost:3000")

        assert client.datetimerfc1123.get_null() is None

        with pytest.raises(DeserializationError):
            client.datetimerfc1123.get_invalid()

        with pytest.raises(DeserializationError):
            client.datetimerfc1123.get_underflow()

        with pytest.raises(DeserializationError):
            client.datetimerfc1123.get_overflow()

        client.datetimerfc1123.get_utc_lowercase_max_date_time()
        client.datetimerfc1123.get_utc_uppercase_max_date_time()
        client.datetimerfc1123.get_utc_min_date_time()

        max_date = isodate.parse_datetime("9999-12-31T23:59:59.999999Z")
        client.datetimerfc1123.put_utc_max_date_time(max_date)

        min_date = isodate.parse_datetime("0001-01-01T00:00:00Z")
        client.datetimerfc1123.put_utc_min_date_time(min_date) 
開發者ID:Azure,項目名稱:autorest.python,代碼行數:25,代碼來源:test_datetime_rfc.py

示例7: is_datetime

# 需要導入模塊: import isodate [as 別名]
# 或者: from isodate import parse_datetime [as 別名]
def is_datetime(instance):
            if not isinstance(instance, str_types):
                return True
            return isodate.parse_datetime(instance) 
開發者ID:remg427,項目名稱:misp42splunk,代碼行數:6,代碼來源:_format.py

示例8: is_date

# 需要導入模塊: import isodate [as 別名]
# 或者: from isodate import parse_datetime [as 別名]
def is_date(instance):
            if not isinstance(instance, str_types):
                return True
            return isodate.parse_datetime(instance) 
開發者ID:getavalon,項目名稱:core,代碼行數:6,代碼來源:_format.py

示例9: datetime

# 需要導入模塊: import isodate [as 別名]
# 或者: from isodate import parse_datetime [as 別名]
def datetime(dt):
        return parse_datetime(dt).replace(tzinfo=utc) 
開發者ID:streamlink,項目名稱:streamlink,代碼行數:4,代碼來源:dash_manifest.py

示例10: iso8601_as_datetime

# 需要導入模塊: import isodate [as 別名]
# 或者: from isodate import parse_datetime [as 別名]
def iso8601_as_datetime(iso,
                        localize=False  # Default into local time zone
                        ):
    try:
        parsed = isodate.parse_datetime(iso)
        if localize and parsed.tzinfo is None:
            parsed = get_localzone().localize(parsed)
        return parsed
    except isodate.isoerror.ISO8601Error as ex:
        raise ValueError("Invalid ISO8601 date")

# TODO: This function exists in datetime as .isoformat() 
開發者ID:perfsonar,項目名稱:pscheduler,代碼行數:14,代碼來源:iso8601.py

示例11: marathon_app_status

# 需要導入模塊: import isodate [as 別名]
# 或者: from isodate import parse_datetime [as 別名]
def marathon_app_status(
    app: MarathonApp,
    marathon_client: MarathonClient,
    dashboard_link: Optional[str],
    deploy_status: int,
    list_tasks: bool = False,
) -> MutableMapping[str, Any]:
    app_status = {
        "tasks_running": app.tasks_running,
        "tasks_healthy": app.tasks_healthy,
        "tasks_staged": app.tasks_staged,
        "tasks_total": app.instances,
        "create_timestamp": isodate.parse_datetime(app.version).timestamp(),
        "deploy_status": marathon_tools.MarathonDeployStatus.tostring(deploy_status),
    }

    app_queue = marathon_tools.get_app_queue(marathon_client, app.id)
    if deploy_status == marathon_tools.MarathonDeployStatus.Delayed:
        _, backoff_seconds = marathon_tools.get_app_queue_status_from_queue(app_queue)
        app_status["backoff_seconds"] = backoff_seconds

    unused_offers_summary = marathon_tools.summarize_unused_offers(app_queue)
    if unused_offers_summary is not None:
        app_status["unused_offers"] = unused_offers_summary

    if dashboard_link:
        app_status["dashboard_url"] = "{}/ui/#/apps/%2F{}".format(
            dashboard_link.rstrip("/"), app.id.lstrip("/")
        )

    if list_tasks is True:
        app_status["tasks"] = []
        for task in app.tasks:
            app_status["tasks"].append(build_marathon_task_dict(task))

    return app_status 
開發者ID:Yelp,項目名稱:paasta,代碼行數:38,代碼來源:instance.py

示例12: paasta_log_line_passes_filter

# 需要導入模塊: import isodate [as 別名]
# 或者: from isodate import parse_datetime [as 別名]
def paasta_log_line_passes_filter(
    line: str,
    levels: Sequence[str],
    service: str,
    components: Iterable[str],
    clusters: Sequence[str],
    instances: Iterable[str],
    start_time: datetime.datetime = None,
    end_time: datetime.datetime = None,
) -> bool:
    """Given a (JSON-formatted) log line, return True if the line should be
    displayed given the provided levels, components, and clusters; return False
    otherwise.
    """
    try:
        parsed_line = json.loads(line)
    except ValueError:
        log.debug("Trouble parsing line as json. Skipping. Line: %r" % line)
        return False

    timestamp = isodate.parse_datetime(parsed_line.get("timestamp"))
    if not check_timestamp_in_range(timestamp, start_time, end_time):
        return False
    return (
        parsed_line.get("level") in levels
        and parsed_line.get("component") in components
        and (
            parsed_line.get("cluster") in clusters
            or parsed_line.get("cluster") == ANY_CLUSTER
        )
        and (instances is None or parsed_line.get("instance") in instances)
    ) 
開發者ID:Yelp,項目名稱:paasta,代碼行數:34,代碼來源:logs.py

示例13: paasta_app_output_passes_filter

# 需要導入模塊: import isodate [as 別名]
# 或者: from isodate import parse_datetime [as 別名]
def paasta_app_output_passes_filter(
    line: str,
    levels: Sequence[str],
    service: str,
    components: Iterable[str],
    clusters: Sequence[str],
    instances: Iterable[str],
    start_time: datetime.datetime = None,
    end_time: datetime.datetime = None,
) -> bool:
    try:
        parsed_line = json.loads(line)
    except ValueError:
        log.debug("Trouble parsing line as json. Skipping. Line: %r" % line)
        return False
    try:
        timestamp = isodate.parse_datetime(parsed_line.get("timestamp"))
    # https://github.com/gweis/isodate/issues/53
    except ValueError:
        return True
    if not check_timestamp_in_range(timestamp, start_time, end_time):
        return False
    return (
        parsed_line.get("component") in components
        and (
            parsed_line.get("cluster") in clusters
            or parsed_line.get("cluster") == ANY_CLUSTER
        )
        and (instances is None or parsed_line.get("instance") in instances)
    ) 
開發者ID:Yelp,項目名稱:paasta,代碼行數:32,代碼來源:logs.py

示例14: test_check_timestamp_in_range_true

# 需要導入模塊: import isodate [as 別名]
# 或者: from isodate import parse_datetime [as 別名]
def test_check_timestamp_in_range_true():
    timestamp = isodate.parse_datetime("2016-06-07T23:46:03+00:00")

    start_time = isodate.parse_datetime("2016-06-07T23:40:03+00:00")
    end_time = isodate.parse_datetime("2016-06-07T23:50:03+00:00")

    assert logs.check_timestamp_in_range(timestamp, start_time, end_time) is True 
開發者ID:Yelp,項目名稱:paasta,代碼行數:9,代碼來源:test_cmds_logs.py

示例15: test_paasta_log_line_passes_filter_true_when_valid_time

# 需要導入模塊: import isodate [as 別名]
# 或者: from isodate import parse_datetime [as 別名]
def test_paasta_log_line_passes_filter_true_when_valid_time():
    service = "fake_service"
    levels = ["fake_level1", "fake_level2"]
    clusters = ["fake_cluster1", "fake_cluster2"]
    instance = "fake_instance"
    instances = [instance]
    components = ["build", "deploy"]
    line = "fake_line"
    formatted_line = format_log_line(
        levels[0],
        clusters[0],
        service,
        instance,
        components[0],
        line,
        timestamp="2016-06-07T23:46:03+00:00",
    )

    start_time = isodate.parse_datetime("2016-06-07T23:40:03+00:00")
    end_time = isodate.parse_datetime("2016-06-07T23:50:03+00:00")

    assert (
        logs.paasta_log_line_passes_filter(
            formatted_line,
            levels,
            service,
            components,
            clusters,
            instances,
            start_time=start_time,
            end_time=end_time,
        )
        is True
    ) 
開發者ID:Yelp,項目名稱:paasta,代碼行數:36,代碼來源:test_cmds_logs.py


注:本文中的isodate.parse_datetime方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。