当前位置: 首页>>代码示例>>Python>>正文


Python arrow.utcnow方法代码示例

本文整理汇总了Python中arrow.utcnow方法的典型用法代码示例。如果您正苦于以下问题:Python arrow.utcnow方法的具体用法?Python arrow.utcnow怎么用?Python arrow.utcnow使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在arrow的用法示例。


在下文中一共展示了arrow.utcnow方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: rename_project

# 需要导入模块: import arrow [as 别名]
# 或者: from arrow import utcnow [as 别名]
def rename_project(self, old_project, new_project):
        """Rename a project in all affected frames."""
        if old_project not in self.projects:
            raise WatsonError(u'Project "%s" does not exist' % old_project)

        updated_at = arrow.utcnow()
        # rename project
        for frame in self.frames:
            if frame.project == old_project:
                self.frames[frame.id] = frame._replace(
                    project=new_project,
                    updated_at=updated_at
                )

        self.frames.changed = True
        self.save() 
开发者ID:TailorDev,项目名称:Watson,代码行数:18,代码来源:watson.py

示例2: rename_tag

# 需要导入模块: import arrow [as 别名]
# 或者: from arrow import utcnow [as 别名]
def rename_tag(self, old_tag, new_tag):
        """Rename a tag in all affected frames."""
        if old_tag not in self.tags:
            raise WatsonError(u'Tag "%s" does not exist' % old_tag)

        updated_at = arrow.utcnow()
        # rename tag
        for frame in self.frames:
            if old_tag in frame.tags:
                self.frames[frame.id] = frame._replace(
                    tags=[new_tag if t == old_tag else t for t in frame.tags],
                    updated_at=updated_at
                )

        self.frames.changed = True
        self.save() 
开发者ID:TailorDev,项目名称:Watson,代码行数:18,代码来源:watson.py

示例3: sync

# 需要导入模块: import arrow [as 别名]
# 或者: from arrow import utcnow [as 别名]
def sync(watson):
    """
    Get the frames from the server and push the new ones.

    The URL of the server and the User Token must be defined via the
    `watson config` command.

    Example:

    \b
    $ watson config backend.url http://localhost:4242
    $ watson config backend.token 7e329263e329
    $ watson sync
    Received 42 frames from the server
    Pushed 23 frames to the server
    """
    last_pull = arrow.utcnow()
    pulled = watson.pull()
    click.echo("Received {} frames from the server".format(len(pulled)))

    pushed = watson.push(last_pull)
    click.echo("Pushed {} frames to the server".format(len(pushed)))

    watson.last_sync = arrow.utcnow()
    watson.save() 
开发者ID:TailorDev,项目名称:Watson,代码行数:27,代码来源:cli.py

示例4: __new__

# 需要导入模块: import arrow [as 别名]
# 或者: from arrow import utcnow [as 别名]
def __new__(cls, start, stop, project, id, tags=None, updated_at=None,):
        try:
            if not isinstance(start, arrow.Arrow):
                start = arrow.get(start)

            if not isinstance(stop, arrow.Arrow):
                stop = arrow.get(stop)

            if updated_at is None:
                updated_at = arrow.utcnow()
            elif not isinstance(updated_at, arrow.Arrow):
                updated_at = arrow.get(updated_at)
        except (ValueError, TypeError) as e:
            from .watson import WatsonError
            raise WatsonError(u"Error converting date: {}".format(e))

        start = start.to('local')
        stop = stop.to('local')

        if tags is None:
            tags = []

        return super(Frame, cls).__new__(
            cls, start, stop, project, id, tags, updated_at
        ) 
开发者ID:TailorDev,项目名称:Watson,代码行数:27,代码来源:frames.py

示例5: test_report_current

# 需要导入模块: import arrow [as 别名]
# 或者: from arrow import utcnow [as 别名]
def test_report_current(mocker, config_dir):
    mocker.patch('arrow.utcnow', return_value=arrow.get(5000))

    watson = Watson(
        current={'project': 'foo', 'start': 4000},
        config_dir=config_dir
    )

    for _ in range(2):
        report = watson.report(
            arrow.utcnow(), arrow.utcnow(), current=True, projects=['foo']
        )
    assert len(report['projects']) == 1
    assert report['projects'][0]['name'] == 'foo'
    assert report['projects'][0]['time'] == pytest.approx(1000)

    report = watson.report(
        arrow.utcnow(), arrow.utcnow(), current=False, projects=['foo']
    )
    assert len(report['projects']) == 0

    report = watson.report(
        arrow.utcnow(), arrow.utcnow(), projects=['foo']
    )
    assert len(report['projects']) == 0 
开发者ID:TailorDev,项目名称:Watson,代码行数:27,代码来源:test_watson.py

示例6: test_current_ranged_loans_filter

# 需要导入模块: import arrow [as 别名]
# 或者: from arrow import utcnow [as 别名]
def test_current_ranged_loans_filter(app):
    """Test ranged current loans filter."""
    with app.app_context():
        rfilter = overdue_loans_filter("field")

        current_loans_query = Terms(
            state=current_app.config["CIRCULATION_STATES_LOAN_ACTIVE"]
        )

        overdue = rfilter(["Overdue"])
        field = {"lt": str(arrow.utcnow().date())}
        assert overdue == Range(field=field) & current_loans_query

        upcoming = rfilter(["Upcoming return"])
        field = {
            "gte": str(arrow.utcnow().date()),
            "lte": str((arrow.utcnow() + timedelta(days=7)).date()),
        }
        assert upcoming == Range(field=field) & current_loans_query 
开发者ID:inveniosoftware,项目名称:invenio-app-ils,代码行数:21,代码来源:test_facets.py

示例7: _create_on_loan_brwreq_with_pending_extension

# 需要导入模块: import arrow [as 别名]
# 或者: from arrow import utcnow [as 别名]
def _create_on_loan_brwreq_with_pending_extension(
    patron_id, client, json_headers
):
    """Create a new ON_LOAN ILL borrowing request with pending extension."""
    today = arrow.utcnow().date().isoformat()
    brwreq, brwreq_pid = _create_on_loan_brwreq_random_dates(
        "1", client, json_headers
    )
    res = _request_extension_action(brwreq_pid, client, json_headers)
    assert res.status_code == 200

    brwreq = res.get_json()["metadata"]
    patron_loan = brwreq["patron_loan"]

    assert patron_loan["loan"]["state"] == "ITEM_ON_LOAN"
    assert "extension_count" not in patron_loan["loan"]
    assert patron_loan["extension"]["status"] == "PENDING"
    assert patron_loan["extension"]["request_date"] == today

    return brwreq, brwreq["pid"] 
开发者ID:inveniosoftware,项目名称:invenio-app-ils,代码行数:22,代码来源:test_ill_brw_reqs_patron_loan_extension_actions.py

示例8: test_brwreq_create_loan_fails_on_loan_pid_already_attached

# 需要导入模块: import arrow [as 别名]
# 或者: from arrow import utcnow [as 别名]
def test_brwreq_create_loan_fails_on_loan_pid_already_attached(
    db, client, testdata, json_headers, users
):
    """Test borrowing requests create loan action fails on loan_pid already."""
    user_login(client, "librarian", users)

    # demo data "illbid-2" has the valid state `REQUESTED`
    pid = "illbid-2"

    rec = BorrowingRequest.get_record_by_pid(pid)
    rec.setdefault("patron_loan", {})
    rec["patron_loan"]["pid"] = "loanid-3"
    rec.commit()
    db.session.commit()

    # already with a loan pid for some reasons
    now = arrow.utcnow()
    future = now + timedelta(days=5)
    data = dict(
        loan_start_date=now.date().isoformat(),
        loan_end_date=future.date().isoformat(),
    )
    _assert_create_loan_action_fails(pid, data, client, json_headers) 
开发者ID:inveniosoftware,项目名称:invenio-app-ils,代码行数:25,代码来源:test_ill_brw_reqs_patron_loan_create_action.py

示例9: overdue_agg

# 需要导入模块: import arrow [as 别名]
# 或者: from arrow import utcnow [as 别名]
def overdue_agg():
    """Create a custom aggregation with dynamic dates."""
    return dict(
        filter=dict(terms=dict(
            state=current_app.config["CIRCULATION_STATES_LOAN_ACTIVE"])),
        aggs=dict(
            end_date=dict(
                range=dict(
                    field="end_date",
                    ranges=[{"key": "Overdue",
                             "to": str(
                                 (arrow.utcnow()).date())},
                            {"key": "Upcoming return",
                             "from": str(arrow.utcnow().date()),
                             "to": str(
                                 current_app.config["CIRCULATION_POLICIES"][
                                     "upcoming_return_range"]().date())
                             }
                            ],
                )
            )
        )
    ) 
开发者ID:inveniosoftware,项目名称:invenio-app-ils,代码行数:25,代码来源:facets.py

示例10: get_timedelta

# 需要导入模块: import arrow [as 别名]
# 或者: from arrow import utcnow [as 别名]
def get_timedelta(expression):

    # TODO: Use pandas' Timedelta. Timedelta('1m2s')
    # http://pandas.pydata.org/pandas-docs/stable/timedeltas.html

    # FIXME: Sanitize expression
    code = expression
    delta_raw = code.replace('now-', '')
    if code != delta_raw:
        code = code.replace(delta_raw, 'delta')

    # "code" should now be "now-delta"
    #print 'code:', code

    now = datetime.utcnow()
    delta = tdelta(delta_raw)

    # FIXME: This is nasty
    try:
        td = eval(code)
    except:
        raise ValueError('Unknown expression: {expression}'.format(expression=expression))

    return td 
开发者ID:daq-tools,项目名称:kotori,代码行数:26,代码来源:influx.py

示例11: print_positions

# 需要导入模块: import arrow [as 别名]
# 或者: from arrow import utcnow [as 别名]
def print_positions(self, ps):
        if not ps:
            return

        symbol = helper.symbol(ps)
        hold_side = "long" if ps.side == OrderSide_Bid else "short" if ps.side == OrderSide_Ask else '--'
        last_tick = self.tick(symbol)
        timestamp = last_tick.utc_time if last_tick else arrow.utcnow()

        transact_time = arrow.get(ps.transact_time).to('local')
        current_time = arrow.get(timestamp).to('local')
        ps_fields = "{} {} volume/today={:.1f}/{:.1f}, available/today = {:.1f}/{:.1f}, frozen/today = {:.1f}/{:.1f}".format(
            symbol,
            hold_side,
            ps.volume,
            ps.volume_today,
            ps.available,
            ps.available_today,
            ps.order_frozen,
            ps.order_frozen_today
        )
        ps_info_ts = "{}, last transact time: {}, current time: {}".format(ps_fields, transact_time, current_time)
        self.logger.info(ps_info_ts) 
开发者ID:myquant,项目名称:strategy,代码行数:25,代码来源:pos_mixin.py

示例12: query_ENTSOE

# 需要导入模块: import arrow [as 别名]
# 或者: from arrow import utcnow [as 别名]
def query_ENTSOE(session, params, target_datetime=None, span=(-48, 24)):
    """
    Makes a standard query to the ENTSOE API with a modifiable set of parameters.
    Allows an existing session to be passed.
    Raises an exception if no API token is found.
    Returns a request object.
    """
    if target_datetime is None:
        target_datetime = arrow.utcnow()
    else:
        # make sure we have an arrow object
        target_datetime = arrow.get(target_datetime)
    params['periodStart'] = target_datetime.shift(hours=span[0]).format('YYYYMMDDHH00')
    params['periodEnd'] = target_datetime.shift(hours=span[1]).format('YYYYMMDDHH00')
    if 'ENTSOE_TOKEN' not in os.environ:
        raise Exception('No ENTSOE_TOKEN found! Please add it into secrets.env!')
        
    # Due to rate limiting, we need to spread our requests across different tokens
    tokens = os.environ['ENTSOE_TOKEN'].split(',')
    
    params['securityToken'] = np.random.choice(tokens)
    return session.get(ENTSOE_ENDPOINT, params=params) 
开发者ID:tmrowco,项目名称:electricitymap-contrib,代码行数:24,代码来源:ENTSOE.py

示例13: expire

# 需要导入模块: import arrow [as 别名]
# 或者: from arrow import utcnow [as 别名]
def expire(ttl):
    """
    Removed all endpoints that have not been recently updated.
    """
    print("[+] Staring expiration of old endpoints.")

    try:
        now = arrow.utcnow()
        expiration = now - timedelta(hours=ttl)
        endpoints = database.session_query(Endpoint).filter(
            cast(Endpoint.last_updated, ArrowType) <= expiration
        )

        for endpoint in endpoints:
            print(
                "[!] Expiring endpoint: {name} Last Updated: {last_updated}".format(
                    name=endpoint.name, last_updated=endpoint.last_updated
                )
            )
            database.delete(endpoint)
            metrics.send("endpoint_expired", "counter", 1)

        print("[+] Finished expiration.")
    except Exception as e:
        sentry.captureException() 
开发者ID:Netflix,项目名称:lemur,代码行数:27,代码来源:cli.py

示例14: query_common_name

# 需要导入模块: import arrow [as 别名]
# 或者: from arrow import utcnow [as 别名]
def query_common_name(common_name, args):
    """
    Helper function that queries for not expired certificates by common name (and owner)

    :param common_name:
    :param args:
    :return:
    """
    owner = args.pop("owner")
    if not owner:
        owner = "%"

    # only not expired certificates
    current_time = arrow.utcnow()

    result = (
        Certificate.query.filter(Certificate.cn.ilike(common_name))
        .filter(Certificate.owner.ilike(owner))
        .filter(Certificate.not_after >= current_time.format("YYYY-MM-DD"))
        .all()
    )

    return result 
开发者ID:Netflix,项目名称:lemur,代码行数:25,代码来源:service.py

示例15: sync

# 需要导入模块: import arrow [as 别名]
# 或者: from arrow import utcnow [as 别名]
def sync(source, user):
    new_certs, updated_certs, updated_certs_by_hash = sync_certificates(source, user)
    new_endpoints, updated_endpoints, updated_endpoints_by_hash = sync_endpoints(source)

    metrics.send("sync.updated_certs_by_hash",
                 "gauge", updated_certs_by_hash,
                 metric_tags={"source": source.label})

    metrics.send("sync.updated_endpoints_by_hash",
                 "gauge", updated_endpoints_by_hash,
                 metric_tags={"source": source.label})

    source.last_run = arrow.utcnow()
    database.update(source)

    return {
        "endpoints": (new_endpoints, updated_endpoints),
        "certificates": (new_certs, updated_certs),
    } 
开发者ID:Netflix,项目名称:lemur,代码行数:21,代码来源:service.py


注:本文中的arrow.utcnow方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。