Python arrow.utcnow() Examples

The following are 30 code examples of arrow.utcnow(). 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 arrow , or try the search function .
Example #1
Source File: plugin.py    From lemur with Apache License 2.0 6 votes vote down vote up
def determine_end_date(end_date):
    """
    Determine appropriate end date

    :param end_date:
    :return: validity_end
    """
    default_years = current_app.config.get("DIGICERT_DEFAULT_VALIDITY", 1)
    max_validity_end = arrow.utcnow().shift(years=current_app.config.get("DIGICERT_MAX_VALIDITY", default_years))

    if not end_date:
        end_date = arrow.utcnow().shift(years=default_years)

    if end_date > max_validity_end:
        end_date = max_validity_end
    return end_date 
Example #2
Source File: test_watson.py    From Watson with MIT License 6 votes vote down vote up
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 
Example #3
Source File: watson.py    From Watson with MIT License 6 votes vote down vote up
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() 
Example #4
Source File: frames.py    From Watson with MIT License 6 votes vote down vote up
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
        ) 
Example #5
Source File: cli.py    From Watson with MIT License 6 votes vote down vote up
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() 
Example #6
Source File: watson.py    From Watson with MIT License 6 votes vote down vote up
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() 
Example #7
Source File: service.py    From lemur with Apache License 2.0 6 votes vote down vote up
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 
Example #8
Source File: missing.py    From lemur with Apache License 2.0 6 votes vote down vote up
def convert_validity_years(data):
    """
    Convert validity years to validity_start and validity_end

    :param data:
    :return:
    """
    if data.get("validity_years"):
        now = arrow.utcnow()
        data["validity_start"] = now.isoformat()

        end = now.shift(years=+int(data["validity_years"]))

        if not current_app.config.get("LEMUR_ALLOW_WEEKEND_EXPIRATION", True):
            if is_weekend(end):
                end = end.shift(days=-2)

        data["validity_end"] = end.isoformat()
    return data 
Example #9
Source File: test_facets.py    From invenio-app-ils with MIT License 6 votes vote down vote up
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 
Example #10
Source File: test_ill_brw_reqs_patron_loan_extension_actions.py    From invenio-app-ils with MIT License 6 votes vote down vote up
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"] 
Example #11
Source File: service.py    From lemur with Apache License 2.0 6 votes vote down vote up
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),
    } 
Example #12
Source File: test_ill_brw_reqs_patron_loan_create_action.py    From invenio-app-ils with MIT License 6 votes vote down vote up
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) 
Example #13
Source File: facets.py    From invenio-app-ils with MIT License 6 votes vote down vote up
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())
                             }
                            ],
                )
            )
        )
    ) 
Example #14
Source File: cli.py    From lemur with Apache License 2.0 6 votes vote down vote up
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() 
Example #15
Source File: influx.py    From kotori with GNU Affero General Public License v3.0 6 votes vote down vote up
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 
Example #16
Source File: ENTSOE.py    From electricitymap-contrib with MIT License 6 votes vote down vote up
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) 
Example #17
Source File: pos_mixin.py    From strategy with Apache License 2.0 6 votes vote down vote up
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) 
Example #18
Source File: test_3_0_ldp.py    From lakesuperior with Apache License 2.0 5 votes vote down vote up
def timeframe(self):
        """
        Times used in these tests: UTC midnight of today, yesterday, tomorrow.
        """
        today = arrow.utcnow().floor('day')
        yesterday = today.shift(days=-1)
        tomorrow = today.shift(days=1)

        path = f'/ldp/{uuid4()}'
        self.client.put(path)

        return path, today, yesterday, tomorrow 
Example #19
Source File: test_missing.py    From lemur with Apache License 2.0 5 votes vote down vote up
def test_convert_validity_years(session):
    from lemur.common.missing import convert_validity_years

    with freeze_time("2016-01-01"):
        data = convert_validity_years(dict(validity_years=2))

        assert data["validity_start"] == arrow.utcnow().isoformat()
        assert data["validity_end"] == arrow.utcnow().shift(years=+2).isoformat()

    with freeze_time("2015-01-10"):
        data = convert_validity_years(dict(validity_years=1))
        assert (
            data["validity_end"]
            == arrow.utcnow().shift(years=+1, days=-2).isoformat()
        ) 
Example #20
Source File: messaging.py    From lemur with Apache License 2.0 5 votes vote down vote up
def needs_notification(certificate):
    """
    Determine if notifications for a given certificate should
    currently be sent

    :param certificate:
    :return:
    """
    now = arrow.utcnow()
    days = (certificate.not_after - now).days

    notifications = []

    for notification in certificate.notifications:
        if not notification.active or not notification.options:
            return

        interval = get_plugin_option("interval", notification.options)
        unit = get_plugin_option("unit", notification.options)

        if unit == "weeks":
            interval *= 7

        elif unit == "months":
            interval *= 30

        elif unit == "days":  # it's nice to be explicit about the base unit
            pass

        else:
            raise Exception(
                "Invalid base unit for expiration interval: {0}".format(unit)
            )

        if days == interval:
            notifications.append(notification)
    return notifications 
Example #21
Source File: messaging.py    From lemur with Apache License 2.0 5 votes vote down vote up
def get_certificates(exclude=None):
    """
    Finds all certificates that are eligible for notifications.
    :param exclude:
    :return:
    """
    now = arrow.utcnow()
    max = now + timedelta(days=90)

    q = (
        database.db.session.query(Certificate)
        .filter(Certificate.not_after <= max)
        .filter(Certificate.notify == True)
        .filter(Certificate.expired == False)
    )  # noqa

    exclude_conditions = []
    if exclude:
        for e in exclude:
            exclude_conditions.append(~Certificate.name.ilike("%{}%".format(e)))

        q = q.filter(and_(*exclude_conditions))

    certs = []

    for c in windowed_query(q, Certificate.id, 10000):
        if needs_notification(c):
            certs.append(c)

    return certs 
Example #22
Source File: models.py    From appointment-reminders-django with MIT License 5 votes vote down vote up
def clean(self):
        """Checks that appointments are not scheduled in the past"""

        appointment_time = arrow.get(self.time, self.time_zone.zone)

        if appointment_time < arrow.utcnow():
            raise ValidationError(
                'You cannot schedule an appointment for the past. '
                'Please check your time and time_zone') 
Example #23
Source File: tests.py    From appointment-reminders-django with MIT License 5 votes vote down vote up
def test_clean_valid_appointment(self, _):
        # Arrange
        time_in_future = arrow.utcnow().replace(minutes=+10)
        appointment = mommy.make(Appointment, time=time_in_future.datetime)

        # Assert
        try:
            appointment.clean()
        except ValidationError:
            self.fail(
                'appointment with time in the past raised ValidationError') 
Example #24
Source File: tests.py    From appointment-reminders-django with MIT License 5 votes vote down vote up
def test_clean_invalid_appointment(self, _):
        # Arrange
        time_in_past = arrow.utcnow().replace(minutes=-10)
        appointment = mommy.make(Appointment, time=time_in_past.datetime)

        # Assert
        with self.assertRaises(ValidationError):
            appointment.clean() 
Example #25
Source File: utils.py    From lexico with MIT License 5 votes vote down vote up
def update_meta(word):
    with sqlite3.connect(DB_FILE) as connection:
        cursor = connection.cursor()
        meta_query = '''SELECT lookup FROM Words WHERE word=(?)'''
        update_statement = '''UPDATE Words SET lookup=(?), last_lookup_at=(?) WHERE word=(?)'''

        cursor.execute(meta_query, [word])
        lookup_count, *dummy = cursor.fetchone()

        now = arrow.utcnow().isoformat()
        cursor.execute(update_statement, [lookup_count+1, now, word]) 
Example #26
Source File: IN.py    From electricitymap-contrib with MIT License 5 votes vote down vote up
def read_datetime_with_only_time(time_string, time_format, now=utcnow()):
    utc = now.floor('hour')
    india_now = utc.to('Asia/Kolkata')
    time = get(time_string, time_format)
    india_date_time = india_now.replace(hour=time.hour, minute=time.minute, second=time.second)
    if india_date_time > india_now:
        india_date_time.shift(days=-1)
    return india_date_time 
Example #27
Source File: AU_solar.py    From electricitymap-contrib with MIT License 5 votes vote down vote up
def fetch_solar_all(session, hours_in_the_past=2):
    data_url = SOLAR_URL
    r = session.post(data_url, {'day': _get_australian_date()})
    data = r.json()

    if data and 'output' in data and data['output']:
        production_data = data['output']

        first_timestamp = arrow.get(production_data[0]['ts'])

        if (arrow.utcnow() - first_timestamp).total_seconds() >= (hours_in_the_past * 60 * 60):
            return production_data
    else:
        production_data = []

    # If we got here, we want to get more data.
    # Requesting yesterday's data in the browser sometimes gives an HTTP 406 Unacceptable error,
    # but it's always worked in the script so far. Could double check and adjust
    # how many hours are fetched if it causes a problem in the future.
    data_url = SOLAR_URL
    r = session.post(data_url, {'day': _get_australian_date(days_in_past=1)})
    data = r.json()

    full_production_data = data['output'] + production_data

    return full_production_data 
Example #28
Source File: AU_solar.py    From electricitymap-contrib with MIT License 5 votes vote down vote up
def _get_australian_date(days_in_past=0):
    utc_now = datetime.datetime.utcnow()

    if utc_now.hour >= 18:
        australian_date = utc_now + datetime.timedelta(days=1)
    else:
        australian_date = utc_now

    australian_date -= datetime.timedelta(days=days_in_past)

    # format as only Y-m-d
    return australian_date.strftime('%Y-%m-%d') 
Example #29
Source File: plugin.py    From lemur with Apache License 2.0 5 votes vote down vote up
def map_cis_fields(options, csr):
    """
    MAP issuer options to DigiCert CIS fields/options.

    :param options:
    :param csr:
    :return: data
    """

    if options.get("validity_years"):
        validity_end = determine_end_date(arrow.utcnow().shift(years=options["validity_years"]))
    elif options.get("validity_end"):
        validity_end = determine_end_date(options.get("validity_end"))
    else:
        validity_end = determine_end_date(False)

    data = {
        "profile_name": current_app.config.get("DIGICERT_CIS_PROFILE_NAMES", {}).get(options['authority'].name),
        "common_name": options["common_name"],
        "additional_dns_names": get_additional_names(options),
        "csr": csr,
        "signature_hash": signature_hash(options.get("signing_algorithm")),
        "validity": {
            "valid_to": validity_end.format("YYYY-MM-DDTHH:MM") + "Z"
        },
        "organization": {
            "name": options["organization"],
            "units": [options["organizational_unit"]],
        },
    }
    #  possibility to default to a SIGNING_ALGORITHM for a given profile
    if current_app.config.get("DIGICERT_CIS_SIGNING_ALGORITHMS", {}).get(options['authority'].name):
        data["signature_hash"] = current_app.config.get("DIGICERT_CIS_SIGNING_ALGORITHMS", {}).get(
            options['authority'].name)

    return data 
Example #30
Source File: restful.py    From stethoscope with Apache License 2.0 5 votes vote down vote up
def transform_to_snapshot(self, devices_by_email):
    since = arrow.utcnow().replace(days=-14)

    snapshot = list()
    for email, devices in six.iteritems(devices_by_email):
      for device in devices:
        if 'last_sync' not in device or device.get('last_sync') < since:
          # ignore devices that haven't synced in more than N days
          continue
        snapshot.append(device)

    return snapshot