Python arrow.Arrow() Examples

The following are 30 code examples of arrow.Arrow(). 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: test_jamf.py    From stethoscope with Apache License 2.0 6 votes vote down vote up
def test_process_basic_information_sanity_checks(device):
  pprint.pprint(device)

  for key in [
    'model',
    'name',
    'platform',
    'serial',
    'source',
    'last_sync',
    'software',
  ]:
    assert key in device

  assert isinstance(device['last_sync'], arrow.Arrow)

  assert device['source'] == 'jamf' 
Example #2
Source File: watson.py    From Watson with MIT License 6 votes vote down vote up
def current(self, value):
        if not value or 'project' not in value:
            self._current = {}

            if self._old_state is None:
                self._old_state = {}

            return

        start = value.get('start', arrow.now())

        if not isinstance(start, arrow.Arrow):
            start = self._parse_date(start)

        self._current = {
            'project': value['project'],
            'start': start,
            'tags': value.get('tags') or []
        }

        if self._old_state is None:
            self._old_state = self._current 
Example #3
Source File: match.py    From cassiopeia with MIT License 6 votes vote down vote up
def __init__(self, *, summoner: Summoner, begin_index: int = None, end_index: int = None, begin_time: arrow.Arrow = None, end_time: arrow.Arrow = None, queues: Set[Queue] = None, seasons: Set[Season] = None, champions: Set[Champion] = None):
        assert end_index is None or end_index > begin_index
        if begin_time is not None and end_time is not None and begin_time > end_time:
            raise ValueError("`end_time` should be greater than `begin_time`")
        kwargs = {"region": summoner.region}
        kwargs["queues"] = queues or []
        kwargs["seasons"] = seasons or []
        champions = champions or []
        kwargs["championIds"] = [champion.id if isinstance(champion, Champion) else champion for champion in champions]
        kwargs["begin_index"] = begin_index
        kwargs["end_index"] = end_index
        if begin_time is not None and not isinstance(begin_time, (int, float)):
            begin_time = begin_time.timestamp * 1000
        kwargs["begin_time"] = begin_time
        if end_time is not None and not isinstance(end_time, (int, float)):
            end_time = end_time.timestamp * 1000
        kwargs["end_time"] = end_time
        assert isinstance(summoner, Summoner)
        self.__account_id_callable = lambda: summoner.account_id
        self.__summoner = summoner
        CassiopeiaObject.__init__(self, **kwargs) 
Example #4
Source File: arrow_utils_test.py    From quantified-self with MIT License 6 votes vote down vote up
def test_is_weekday(self):

        mon = arrow.Arrow(2017, 8, 14).weekday()
        tue = arrow.Arrow(2017, 8, 15).weekday()
        wed = arrow.Arrow(2017, 8, 16).weekday()
        thu = arrow.Arrow(2017, 8, 17).weekday()
        fri = arrow.Arrow(2017, 8, 18).weekday()
        sat = arrow.Arrow(2017, 8, 19).weekday()
        sun = arrow.Arrow(2017, 8, 20).weekday()

        self.assertEqual(mon < 5, True)
        self.assertEqual(tue < 5, True)
        self.assertEqual(wed < 5, True)
        self.assertEqual(thu < 5, True)
        self.assertEqual(fri < 5, True)
        self.assertEqual(sat < 5, False)
        self.assertEqual(sun < 5, False) 
Example #5
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 #6
Source File: arrow_utils_test.py    From quantified-self with MIT License 6 votes vote down vote up
def test_is_between(self):
        self.assertEqual(
            ArrowUtil.is_between((10, 0), (20, 0), now=arrow.Arrow(2017, 8, 14, 12, 0)),
            True,
        )
        self.assertEqual(
            ArrowUtil.is_between((0, 0), (24, 0), now=arrow.Arrow(2017, 8, 14, 12, 0)),
            True,
        )
        self.assertEqual(
            ArrowUtil.is_between((10, 0), (24, 0), now=arrow.Arrow(2017, 8, 14, 9, 0)),
            False,
        )
        self.assertEqual(
            ArrowUtil.is_between((10, 0), (20, 0), now=arrow.Arrow(2017, 8, 14, 10, 0)),
            True,
        )
        self.assertEqual(
            ArrowUtil.is_between((10, 0), (20, 0), now=arrow.Arrow(2017, 8, 14, 20, 0)),
            True,
        ) 
Example #7
Source File: util.py    From clusterman with Apache License 2.0 6 votes vote down vote up
def autoscaling_is_paused(cluster: str, pool: str, scheduler: str, timestamp: arrow.Arrow) -> bool:
    response = dynamodb.get_item(
        TableName=CLUSTERMAN_STATE_TABLE,
        Key={
            'state': {'S': AUTOSCALER_PAUSED},
            'entity': {'S': f'{cluster}.{pool}.{scheduler}'},
        },
        ConsistentRead=True,
    )
    if 'Item' not in response:
        return False

    if (
        'expiration_timestamp' in response['Item'] and
        timestamp.timestamp > int(response['Item']['expiration_timestamp']['N'])
    ):
        return False

    return True 
Example #8
Source File: test_championmastery.py    From cassiopeia with MIT License 6 votes vote down vote up
def test_mastery_return():
    summoner = cassiopeia.get_summoner(name=SUMMONER_NAME, region="NA")
    champion = cassiopeia.get_champion(CHAMP_NAME, region="NA")
    champion_mastery = cassiopeia.get_champion_mastery(summoner=summoner.id, champion=champion, region="NA")

    assert isinstance(champion_mastery, cassiopeia.ChampionMastery)
    assert isinstance(champion_mastery.summoner, cassiopeia.Summoner)
    assert isinstance(champion_mastery.champion, cassiopeia.Champion)

    assert champion_mastery.summoner == summoner
    assert champion_mastery.champion == champion

    assert isinstance(champion_mastery.platform, Platform)
    assert isinstance(champion_mastery.region, Region)
    assert isinstance(champion_mastery.chest_granted, bool)
    assert isinstance(champion_mastery.last_played, arrow.Arrow)
    assert isinstance(champion_mastery.level, int) and champion_mastery.level <= 7
    assert isinstance(champion_mastery.points, int)
    assert isinstance(champion_mastery.points_since_last_level, int)
    assert isinstance(champion_mastery.points_until_next_level, int) 
Example #9
Source File: date.py    From junction with MIT License 5 votes vote down vote up
def fromnow(value):
    """
    A wrapper around arrow.humanize(), returns natural time which is less precise than
    django's naturaltime filter. It doesn't display weeks and combination of days & hours.
    """
    if not (
        isinstance(value, date) or isinstance(value, arrow.Arrow)
    ):  # datetime is a subclass of date
        return value

    return arrow.get(value).humanize() 
Example #10
Source File: autoscaler.py    From clusterman with Apache License 2.0 5 votes vote down vote up
def _get_smoothed_non_zero_metadata(
        self,
        metric_name: str,
        time_start: arrow.Arrow,
        time_end: arrow.Arrow,
        smoothing: int = 5,
    ) -> Optional[Tuple[int, int, float]]:
        """ Compute some smoothed-out historical metrics metadata

        :param metric_name: the metadata metric to query
        :param time_start: the beginning of the historical time window to query
        :param time_end: the end of the historical time window to query
        :param smoothing: take this many non-zero metric values and average them together
        :returns: the start and end times over which the average was taken, and smoothed-out metric value during this
            time period; or None, if no historical data exists
        """
        metrics = self.metrics_client.get_metric_values(
            metric_name,
            METADATA,
            time_start,
            time_end,
            extra_dimensions=get_cluster_dimensions(self.cluster, self.pool, self.scheduler),
        )[metric_name]
        latest_non_zero_values = [(ts, val) for ts, val in metrics if val > 0][-smoothing:]
        if not latest_non_zero_values:
            return None
        return (
            latest_non_zero_values[0][0],
            latest_non_zero_values[-1][0],
            sum([float(val) for __, val in latest_non_zero_values]) / len(latest_non_zero_values),
        ) 
Example #11
Source File: autoscaler.py    From clusterman with Apache License 2.0 5 votes vote down vote up
def run(self, dry_run: bool = False, timestamp: Optional[arrow.Arrow] = None) -> None:
        """ Do a single check to scale the fleet up or down if necessary.

        :param dry_run: boolean; if True, don't modify the pool size, just print what would happen
        :param timestamp: an arrow object indicating the current time
        """

        timestamp = timestamp or arrow.utcnow()
        logger.info(f'Autoscaling run starting at {timestamp}')
        if autoscaling_is_paused(self.cluster, self.pool, self.scheduler, timestamp):
            logger.info('Autoscaling is currently paused; doing nothing')
            return

        try:
            signal_name = self.signal.name
            resource_request = self.signal.evaluate(timestamp)
            exception = None
        except Exception as e:
            logger.error(f'Client signal {self.signal.name} failed; using default signal')
            signal_name = self.default_signal.name
            resource_request = self.default_signal.evaluate(timestamp)
            exception, tb = e, traceback.format_exc()

        logger.info(f'Signal {signal_name} requested {resource_request}')
        self.pool_manager.reload_state()
        new_target_capacity = self._compute_target_capacity(resource_request)

        self.target_capacity_gauge.set(new_target_capacity, {'dry_run': dry_run})
        self._emit_requested_resource_metrics(resource_request, dry_run=dry_run)

        self.pool_manager.modify_target_capacity(new_target_capacity, dry_run=dry_run)

        if exception:
            logger.error(f'The client signal failed with:\n{tb}')
            raise exception 
Example #12
Source File: io.py    From clusterman with Apache License 2.0 5 votes vote down vote up
def _register_handlers():
    # These operations are idempotent, it's safe to do more than once
    jsonpickle.handlers.register(arrow.Arrow, ArrowSerializer)
    jsonpickle.handlers.register(SortedDict, SortedDictSerializer) 
Example #13
Source File: simulator.py    From clusterman with Apache License 2.0 5 votes vote down vote up
def get_data(
        self,
        key: str,
        start_time: Optional[Arrow] = None,
        end_time: Optional[Arrow] = None,
        step: Optional[timedelta] = None,
    ) -> 'SortedDict[Arrow, float]':
        """ Compute the capacity for the cluster in the specified time range, grouped into chunks

        :param key: the type of data to retreive; must correspond to a key in REPORT_TYPES
        :param start_time: the lower bound of the range (if None, use simulation start time)
        :param end_time: the upper bound of the range (if None, use simulation end time)
        :param step: the width of time for each chunk
        :returns: a list of CPU capacities for the cluster from start_time to end_time
        """
        start_time = start_time or self.start_time
        end_time = end_time or self.end_time
        if key == 'cpus':
            return self.mesos_cpus.values(start_time, end_time, step)
        elif key == 'cpus_allocated':
            return self.mesos_cpus_allocated.values(start_time, end_time, step)
        elif key == 'unused_cpus':
            # If an agent hasn't joined the cluster yet, we'll treat it as "unused" in the simulation
            unused_cpus = self.aws_cpus - self.mesos_cpus_allocated
            return unused_cpus.values(start_time, end_time, step)
        elif key == 'cost':
            return self.cost_per_hour.integrals(start_time, end_time, step, transform=hour_transform)
        elif key == 'unused_cpus_cost':
            # Here we treat CPUs that haven't joined the Mesos cluster as un-allocated.  It's arguable
            # if that's the right way to do this or not.
            percent_unallocated = (self.aws_cpus - self.mesos_cpus_allocated) / self.aws_cpus
            percent_cost = percent_unallocated * self.cost_per_hour
            return percent_cost.integrals(start_time, end_time, step, transform=hour_transform)
        elif key == 'cost_per_cpu':
            cost_per_cpu = self.cost_per_hour / self.aws_cpus
            return cost_per_cpu.values(start_time, end_time, step)
        elif key == 'oversubscribed':
            max_fn = piecewise_max(self.mesos_cpus_allocated - self.aws_cpus, PiecewiseConstantFunction())
            return max_fn.values(start_time, end_time, step)
        else:
            raise ValueError(f'Data key {key} is not recognized') 
Example #14
Source File: queue.py    From clusterman with Apache License 2.0 5 votes vote down vote up
def __init__(self, cluster_name: str) -> None:
        self.client = sqs
        self.cluster = cluster_name
        self.drain_queue_url = staticconf.read_string(f'clusters.{cluster_name}.drain_queue_url')
        self.termination_queue_url = staticconf.read_string(f'clusters.{cluster_name}.termination_queue_url')
        self.draining_host_ttl_cache: Dict[str, arrow.Arrow] = {}
        self.warning_queue_url = staticconf.read_string(
            f'clusters.{cluster_name}.warning_queue_url',
            default=None,
        ) 
Example #15
Source File: match.py    From cassiopeia with MIT License 5 votes vote down vote up
def __get_query_from_kwargs__(cls, *, summoner: Summoner, begin_index: int = None, end_index: int = None, begin_time: arrow.Arrow = None, end_time: arrow.Arrow = None, queues: Set[Queue] = None, seasons: Set[Season] = None, champions: Set[Champion] = None):
        assert isinstance(summoner, Summoner)
        query = {"region": summoner.region}
        query["accountId"] = summoner.account_id

        if begin_index is not None:
            query["beginIndex"] = begin_index

        if end_index is not None:
            query["endIndex"] = end_index

        if begin_time is not None:
            if isinstance(begin_time, arrow.Arrow):
                begin_time = begin_time.timestamp * 1000
            query["beginTime"] = begin_time

        if end_time is not None:
            if isinstance(end_time, arrow.Arrow):
                end_time = end_time.timestamp * 1000
            query["endTime"] = end_time

        if queues is not None:
            query["queues"] = queues

        if seasons is not None:
            query["seasons"] = seasons

        if champions is not None:
            champions = [champion.id if isinstance(champion, Champion) else champion for champion in champions]
            query["champion.ids"] = champions

        return query 
Example #16
Source File: busplus.py    From apex-sigma-core with GNU General Public License v3.0 5 votes vote down vote up
def make_time_list(terminus_times: list, current_time: arrow.Arrow, data_pool: str):
    """

    :param terminus_times:
    :type terminus_times:
    :param current_time:
    :type current_time:
    :param data_pool:
    :type data_pool:
    :return:
    :rtype:
    """
    time_list = []
    previous_hour = int(current_time.shift(hours=-1).format('HH'))
    current_hour = int(current_time.format('HH'))
    next_hour = int(current_time.shift(hours=1).format('HH'))
    prev_hr = find_hr(terminus_times, previous_hour)
    curr_hr = find_hr(terminus_times, current_hour)
    next_hr = find_hr(terminus_times, next_hour)
    for hour_set in [prev_hr, curr_hr, next_hr]:
        if hour_set:
            hour = hour_set.get('hour')
            minute_set = hour_set.get(data_pool)
            for minutes in minute_set:
                time_list.append(make_time(hour, minutes))
    return time_list 
Example #17
Source File: finalfantasyxivtimers.py    From apex-sigma-core with GNU General Public License v3.0 5 votes vote down vote up
def next_daily():
    """
    Gets the next daily timer.
    :return:
    :rtype: arrow.Arrow
    """
    now = arrow.utcnow()
    ttd = arrow.get(arrow.utcnow().format('YYYY-MM-DD 15:00:ssZZ'))
    while now > ttd:
        ttd = ttd.shift(days=1)
    return ttd 
Example #18
Source File: finalfantasyxivtimers.py    From apex-sigma-core with GNU General Public License v3.0 5 votes vote down vote up
def next_weekly():
    """
    Gets the next weekly timer.
    :return:
    :rtype: arrow.Arrow
    """
    starting_point = '2019-05-14 08:00:00+00:00'
    now = arrow.utcnow()
    ttw = arrow.get(starting_point)
    while now > ttw:
        ttw = ttw.shift(days=7)
    return ttw 
Example #19
Source File: common.py    From python_withings_api with MIT License 5 votes vote down vote up
def arrow_or_raise(value: Any) -> Arrow:
    """Return Arrow or raise exception."""
    return enforce_type(arrow_or_none(value), Arrow) 
Example #20
Source File: util.py    From douyin_downloader with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, version=APPINFO['version_code']):
        super(SignUtil, self).__init__()
        self.version = version
        self.sign = {"expired": arrow.Arrow(2000, 1, 1, 0, 0, 0), "common_params": None, "token":None}
        self.s = asks.Session(_API, connections=5) 
Example #21
Source File: test_landesk.py    From stethoscope with Apache License 2.0 5 votes vote down vote up
def check_processed_device(device):
  keys = [
    'model',
    'name',
    'serial',
    'source',
    'type',
    'last_sync',
  ]
  for key in keys:
    assert key in device

  assert isinstance(device['last_sync'], arrow.Arrow)
  assert device['serial'] == '0xDECAFBAD'
  assert device['source'] == 'landesk' 
Example #22
Source File: utils.py    From stethoscope with Apache License 2.0 5 votes vote down vote up
def parse_parameters_list(dict_list):
  """

  >>> import arrow
  >>> returned = parse_parameters_list([
  ...   { "name": "accounts:is_2sv_enrolled", "boolValue": False },
  ...   { "name": "accounts:last_name", "stringValue": "Smith" },
  ...   { "name": "accounts:drive_used_quota_in_mb", "intValue": "0" },
  ...   { "name": "accounts:creation_time",
  ...     "datetimeValue": "2010-10-28T10:26:35.000Z" },
  ... ])
  >>> returned == {
  ...   "accounts:is_2sv_enrolled": False,
  ...   "accounts:last_name": "Smith",
  ...   "accounts:drive_used_quota_in_mb": 0,
  ...   "accounts:creation_time": arrow.Arrow(2010, 10, 28, 10, 26, 35),
  ... }
  True

  >>> parse_parameters_list([{ "name": "fakeValue", "otherType": False }])
  Traceback (most recent call last):
    ...
  ValueError: Failed to determine appropriate type for parameter 'fakeValue'

  """

  retval = dict()
  for item_dict in dict_list:
    if 'boolValue' in item_dict:
      value = item_dict['boolValue']
    elif 'intValue' in item_dict:
      value = int(item_dict['intValue'])
    elif 'stringValue' in item_dict:
      value = item_dict['stringValue']
    elif 'datetimeValue' in item_dict:
      value = arrow.get(item_dict['datetimeValue'])
    else:
      raise ValueError("Failed to determine appropriate type for parameter "
                       "{!r}".format(item_dict['name']))
    retval[item_dict['name']] = value
  return retval 
Example #23
Source File: utils.py    From stethoscope with Apache License 2.0 5 votes vote down vote up
def json_serialize_datetime(obj):
  """Serialize a `datetime.datetime` or `arrow.Arrow` by converting to string in ISO format.

  >>> import json
  >>> json.dumps(arrow.get("2015-05-16 10:37"), default=json_serialize_datetime)
  '"2015-05-16T10:37:00+00:00"'
  >>> json.dumps(datetime.datetime.utcfromtimestamp(1431772620), default=json_serialize_datetime)
  '"2015-05-16T10:37:00"'

  """
  if isinstance(obj, (datetime.datetime, arrow.Arrow)):
    return obj.isoformat(b'T' if six.PY2 else 'T')
  raise TypeError("{!r} is not JSON serializable".format(obj)) 
Example #24
Source File: patch.py    From cassiopeia with MIT License 5 votes vote down vote up
def end(self) -> arrow.Arrow:
        return self._end 
Example #25
Source File: patch.py    From cassiopeia with MIT License 5 votes vote down vote up
def start(self) -> arrow.Arrow:
        return self._start 
Example #26
Source File: patch.py    From cassiopeia with MIT License 5 votes vote down vote up
def from_date(cls, date: Union[arrow.Arrow], region: Union[Region, str] = None) -> "Patch":
        if not cls.__patches:
            cls.__load__()
        if region is None:
            region = configuration.settings.default_region
        if not isinstance(region, Region):
            region = Region(region)
        for patch in cls.__patches[region]:
            patch_end = patch.end or arrow.now().shift(seconds=1)
            if patch.start <= date < patch_end:
                return patch
        else:
            raise ValueError("Unknown patch date {}".format(date)) 
Example #27
Source File: patch.py    From cassiopeia with MIT License 5 votes vote down vote up
def __init__(self, region: Union[str, Region], season: Season, name: str, start: Union[arrow.Arrow, float], end: Optional[Union[arrow.Arrow, float]]):
        if not isinstance(start, arrow.Arrow):
            start = arrow.get(start)
        if end is not None and not isinstance(end, arrow.Arrow):
            end = arrow.get(end)
        if not isinstance(region, Region):
            region = Region(region)
        self._region = region
        self._season = season
        self._name = name
        self._start = start
        self._end = end 
Example #28
Source File: spectator.py    From cassiopeia with MIT License 5 votes vote down vote up
def creation(self) -> arrow.Arrow:
        return arrow.get(self._data[CurrentGameInfoData].creation / 1000) 
Example #29
Source File: champion.py    From cassiopeia with MIT License 5 votes vote down vote up
def release_date(self) -> arrow.Arrow:
        return arrow.get(self._data[ChampionReleaseData].releaseDate) 
Example #30
Source File: championmastery.py    From cassiopeia with MIT License 5 votes vote down vote up
def last_played(self) -> arrow.Arrow:
        """Last time this champion was played by this player."""
        return arrow.get(self._data[ChampionMasteryData].lastPlayed / 1000)