Python源码示例:arrow.Arrow()
示例1
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
示例2
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
)
示例3
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)
示例4
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,
)
示例5
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)
示例6
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)
示例7
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'
示例8
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
示例9
def _parse_date(self, date):
"""Returns Arrow object from timestamp."""
return arrow.Arrow.utcfromtimestamp(date).to('local')
示例10
def _format_date(self, date):
"""Returns timestamp from string timestamp or Arrow object."""
if not isinstance(date, arrow.Arrow):
date = arrow.get(date)
return date.timestamp
示例11
def last_sync(self, value):
if not value:
self._last_sync = arrow.get(0)
return
if not isinstance(value, arrow.Arrow):
value = self._parse_date(value)
self._last_sync = value
示例12
def get_start_time_for_period(period):
# Using now() from datetime instead of arrow for mocking compatibility.
now = arrow.Arrow.fromdatetime(datetime.datetime.now())
date = now.date()
day = date.day
month = date.month
year = date.year
weekday = now.weekday()
if period == 'day':
start_time = arrow.Arrow(year, month, day)
elif period == 'week':
start_time = arrow.Arrow.fromdate(now.shift(days=-weekday).date())
elif period == 'month':
start_time = arrow.Arrow(year, month, 1)
elif period == 'luna':
start_time = get_last_full_moon(now)
elif period == 'year':
start_time = arrow.Arrow(year, 1, 1)
elif period == 'all':
# approximately timestamp `0`
start_time = arrow.Arrow(1970, 1, 1)
else:
raise ValueError(u'Unsupported period value: {}'.format(period))
return start_time
示例13
def test_with_known_date():
aniceday = arrow.Arrow(2018, 7, 27, 10, 51)
aniceday_lastMoon = arrow.Arrow(2018, 6, 28, 4, 55)
aniceday_result = get_last_full_moon(aniceday)
assert aniceday_result == aniceday_lastMoon
thenextday = aniceday.shift(days=1)
thenextday_lastMoon = arrow.Arrow(2018, 7, 27, 20, 22)
thenextday_result = get_last_full_moon(thenextday)
assert thenextday_result == thenextday_lastMoon
示例14
def test_invalid_ranges():
fail = arrow.Arrow(1970, 1, 1)
fail2 = arrow.Arrow(2100, 5, 5)
with pytest.raises(ValueError):
get_last_full_moon(fail)
with pytest.raises(ValueError):
get_last_full_moon(fail2)
示例15
def test_start_new_project(watson):
watson.start('foo', ['A', 'B'])
assert watson.current != {}
assert watson.is_started is True
assert watson.current.get('project') == 'foo'
assert isinstance(watson.current.get('start'), arrow.Arrow)
assert watson.current.get('tags') == ['A', 'B']
示例16
def test_start_new_project_without_tags(watson):
watson.start('foo')
assert watson.current != {}
assert watson.is_started is True
assert watson.current.get('project') == 'foo'
assert isinstance(watson.current.get('start'), arrow.Arrow)
assert watson.current.get('tags') == []
示例17
def test_stop_started_project_without_tags(watson):
watson.start('foo')
watson.stop()
assert watson.current == {}
assert watson.is_started is False
assert len(watson.frames) == 1
assert watson.frames[0].project == 'foo'
assert isinstance(watson.frames[0].start, arrow.Arrow)
assert isinstance(watson.frames[0].stop, arrow.Arrow)
assert watson.frames[0].tags == []
示例18
def validate(self, value, session=None):
if isinstance(value, (float, int)):
value = arrow.Arrow.fromtimestamp(value)
elif not isinstance(value, arrow.Arrow):
raise ValueError("Value must be timestamp or arrow.Arrow instance.")
return value
示例19
def stat(self, **kwargs):
"""Gets information about an object."""
url_endpoint, params, headers, _ = self._get_parameters(**kwargs)
resp = self.get_requests_session().head(
url_endpoint, params=params, headers=headers)
if resp.ok:
return location.LocationStat.from_keywords(
session=self._session,
location=self,
size=resp.headers["x-goog-stored-content-length"],
generation=resp.headers["x-goog-generation"],
created=arrow.Arrow(*(rfc822.parsedate(
resp.headers["Last-Modified"])[:7])).timestamp,
)
示例20
def _coerce_timestamp(value):
if isinstance(value, arrow.Arrow):
return value.float_timestamp
return float(value)
示例21
def _coerce_timestamp(value):
if isinstance(value, arrow.Arrow):
return value.float_timestamp
return float(value)
示例22
def default(self, obj):
if isinstance(obj, arrow.Arrow):
return obj.for_json()
elif isinstance(obj, datetime.datetime):
return obj.strftime('%Y-%m-%dT%H:%M:%SZ')
elif isinstance(obj, datetime.date):
return obj.strftime('%Y-%m-%d')
# Let the base class default method raise the TypeError
return json.JSONEncoder.default(self, obj)
示例23
def default(self, o):
if isinstance(o, arrow.Arrow):
return o.for_json()
else:
return super(self.__class__, self).default(o)
示例24
def get_action_time(time: str) -> arrow.Arrow:
time_str = time.strip().replace("at", "")
if time_str == "now":
return arrow.get(arrow.now(), tzinfo=tz.tzlocal())
else:
return arrow.get(time_str, "MMMM D, YYYY hh:mma", tzinfo=tz.tzlocal())
示例25
def test_get_curr_time_diff(self):
start = arrow.Arrow(2017, 8, 14, 12, 0)
end = arrow.Arrow(2017, 8, 14, 13, 0)
self.assertEqual(ArrowUtil.get_curr_time_diff(start=start, stop=end), 60)
self.assertEqual(
ArrowUtil.get_curr_time_diff(start=start, stop=end, base_hour=True), 1
)
示例26
def datetime_to_str(d):
"""
:param arrow.Arrow d:
:return str:
"""
datetime_str = d.to('utc').isoformat()
if datetime_str.endswith('+00:00'):
datetime_str = datetime_str[:-6] + 'Z'
return datetime_str
示例27
def str_to_datetime(s):
"""
:param str s:
:return arrow.Arrow:
"""
return arrow.get(s)
示例28
def datetime_to_timestamp(d):
"""
:param arrow.Arrow d: A datetime object.
:return float: An equivalent UNIX timestamp.
"""
return d.float_timestamp
示例29
def is_date_class(val):
return isinstance(val, (datetime.date, datetime.datetime, arrow.Arrow, ))
# Calculate seconds since 1970-01-01 (timestamp) in a way that works in
# Python 2 and Python3
# https://docs.python.org/3/library/datetime.html#datetime.datetime.timestamp
示例30
def start(self, region: Region) -> arrow.Arrow:
from .core import Patch
if Patch._Patch__patches is None:
Patch.__load__()
for patch in Patch._Patch__patches[region]:
if patch.season == self:
return patch.start