本文整理汇总了Python中arrow.Arrow类的典型用法代码示例。如果您正苦于以下问题:Python Arrow类的具体用法?Python Arrow怎么用?Python Arrow使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Arrow类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: parse_stamps
def parse_stamps(self, expr=STAMP_RE, fmt='%H:%M, %d %B %Y (%Z)'):
stamps = []
algo = self.archiver.config['algo']
try:
maxage = str2time(re.search(r"^old\((\w+)\)$", algo).group(1))
except AttributeError as e:
e.args = ("Malformed archive algorithm",)
raise ArchiveError(e)
for thread in self.threads:
if mwp_parse(thread['header']).get(0).level != 2:
# the header is not level 2
stamps = []
continue
for stamp in expr.finditer(thread['content']):
# This for loop can probably be optimised, but ain't nobody
# got time fo' dat
#if stamp.group(1) in MONTHS:
try:
stamps.append(Arrow.strptime(stamp.group(0), fmt))
except ValueError: # Invalid stamps should not be parsed, ever
continue
if stamps:
# The most recent stamp should be used to see if we should archive
most_recent = max(stamps)
thread['stamp'] = most_recent
thread['oldenough'] = Arrow.utcnow() - most_recent > maxage
pass # No stamps were found, abandon thread
stamps = []
示例2: friendly_time
def friendly_time(jinja_ctx, context, **kw):
"""Format timestamp in human readable format.
* Context must be a datetimeobject
* Takes optional keyword argument timezone which is a timezone name as a string. Assume the source datetime is in this timezone.
"""
now = context
if not now:
return ""
tz = kw.get("source_timezone", None)
if tz:
tz = timezone(tz)
else:
tz = datetime.timezone.utc
# Meke relative time between two timestamps
now = now.astimezone(tz)
arrow = Arrow.fromdatetime(now)
other = Arrow.fromdatetime(datetime.datetime.utcnow())
return arrow.humanize(other)
示例3: test_local_to_utc
def test_local_to_utc(self):
arr = Arrow(datetime.now(), tz='local')
result = arr.to('UTC')
self.assert_dt_equal(result.datetime, datetime.utcnow())
self.assert_ts_equal(result.timestamp, time.time())
示例4: fire_arrow
def fire_arrow(self, person):
if person.cooldown < 0:
person.cooldown = 0.6
self.arrow_sound.play()
position = (person.position.x, person.position.z)
arrow = Arrow(self.arrowTex, self.program, 1, 1, position, person.collisionMap, self.normal_mesh)
arrow.point(person.angle)
self.arrows.append(arrow)
示例5: test_eq_utc_converstions
def test_eq_utc_converstions(self):
arr = Arrow(datetime(11, 1, 1))
utc_1 = arr.utc()
utc_2 = arr.to('UTC')
self.assertEqual(utc_1.datetime, utc_2.datetime)
self.assertEqual(utc_1, utc_2)
示例6: get_for
def get_for(date):
date = date.replace(tzinfo='utc')
for week in get_dates(access_token):
for day, visits in week:
if day == date:
return VisitResult(
visits, # visits for day
Arrow.now(AU_PERTH) # when data was retrieved
)
return VisitResult([], Arrow.now(AU_PERTH))
示例7: cached_get_for
def cached_get_for(date):
if not hasattr(cached_get_for, '_cache'):
cached_get_for._cache = {}
if date in cached_get_for._cache:
data, timestamp = cached_get_for._cache[date]
if (Arrow.now() - timestamp) < timedelta(hours=1):
return data
cached_get_for._cache[date] = (get_for(date), Arrow.now())
return cached_get_for._cache[date][0]
示例8: user_action_stat
def user_action_stat(interval,user_out_name,song_out_name):
#统计用户三日的数据量
## step 1: 读入数据
base_time = 1426348800 #3-15-0-0-0的unix时间戳
base_time_stamp = Arrow.fromtimestamp(base_time)
interval_seconds = interval * 24 * 3600
parts = load_csv_as_dict('%s/data_source/%s' %(PROJECT_PATH,'mars_tianchi_user_actions.csv'))
user_dict = defaultdict(
lambda: defaultdict(lambda: defaultdict(lambda: 0.0))) # 默认dict的一个trick!
song_dict = defaultdict(lambda:defaultdict(lambda:defaultdict(lambda:0.0)))
count = 0
## step 2:统计数据
for part in parts:
user_id = part['user_id']
song_id = part['song_id']
action_type = part['action_type']
gmt_create = eval(part['gmt_create'])
date_interval_belong = int((Arrow.fromtimestamp(gmt_create) - base_time_stamp).total_seconds())/interval_seconds
user_dict[user_id][date_interval_belong][action_type] += 1
song_dict[song_id][date_interval_belong][action_type] += 1
count += 1
if count % 1000 == 0:
print 'statistical %s records' % count
print 'total users: %s' % len(user_dict)
print 'total songs: %s' % len(song_dict)
## step 3:写入到feature文件
fs = open('%s/feature/%s.csv' % (PROJECT_PATH,user_out_name),'w')
fs.write('user_id,date_interval_%s ,plays,downloads,favors\n' % interval)
count = 0
for user in user_dict:
date_dict = user_dict[user]
for date in date_dict:
action = date_dict[date]
fs.write('%s,%s,%s,%s,%s\n' % (user,date,action['1'],action['2'],action['3']))
count = count + 1
if count % 1000 == 0:
print 'write %s length' % count
fs.close()
print 'user_dict is write done'
fs = open('%s/feature/%s.csv' % (PROJECT_PATH,song_out_name),'w')
fs.write('song_id,date_interval_%s,plays,downloads,favors\n' % interval)
count = 0
for song in song_dict:
date_dict = song_dict[song]
for date in date_dict:
action = date_dict[date]
fs.write('%s,%s,%s,%s,%s\n' % (song,date,action['1'],action['2'],action['3']))
count += 1
if count % 1000 == 0:
print 'write %s length' % count
fs.close()
print 'song_dict is write done'
示例9: test_zone_to_zone
def test_zone_to_zone(self):
dt_1 = datetime.utcnow() + timedelta(hours=-2)
dt_2 = datetime.utcnow() + timedelta(hours=2)
arr_1 = Arrow(dt_1, timedelta(hours=-2))
arr_2 = Arrow(dt_2, timedelta(hours=2))
result_1 = arr_1.to(timedelta(hours=2))
result_2 = arr_2.to(timedelta(hours=-2))
self.assert_dt_equal(result_1.datetime, arr_2.datetime)
self.assert_dt_equal(result_2.datetime, arr_1.datetime)
示例10: menu
def menu(window, clock):
arrow_right = Arrow("right", window.get_size())
arrow_left = Arrow("left", window.get_size())
loop = True
while loop:
for event in pygame.event.get():
if event.type == QUIT:
loop = False
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
loop = False
if event.key == K_RIGHT:
print "right"
arrow_right.big = True
if event.key == K_LEFT:
print "left"
arrow_left.big = True
window.fill((30,130,184))
arrow_right.draw(window)
arrow_left.draw(window)
pygame.display.flip()
clock.tick(30)
示例11: _process_dates
def _process_dates(self):
"""internal method to parse the gcal_url for start and end date info and
set the _start_date_arrow and _end_date_arrow to instances of arrow objs
"""
#dont rerun if _start_date_arrow or _end_date_arrow is set or if gcal_url not found
if (self._start_date_arrow or self._end_date_arrow) or not self.gcal_url: return
gcal_url = self.gcal_url
gcal_url_date_time_match = self.gcal_url_date_time_pattern.search(gcal_url)
if not gcal_url_date_time_match: return
(gcal_url_start_date_str, gcal_url_end_date_str) = gcal_url_date_time_match.groups()
# add time to date if no time spesified
if 'T' not in gcal_url_start_date_str: gcal_url_start_date_str += 'T000000'
if 'T' not in gcal_url_end_date_str: gcal_url_end_date_str += 'T000000'
self._start_date_arrow = Arrow.strptime(gcal_url_start_date_str, self.gcal_url_date_time_format, tzinfo=self.event_timezone)
self._end_date_arrow = Arrow.strptime(gcal_url_end_date_str, self.gcal_url_date_time_format, tzinfo=self.event_timezone)
示例12: now
def now(tz=None):
'''Returns an :class:`Arrow <arrow.Arrow>` object, representing "now".
:param tz: (optional) An expression representing a timezone. Defaults to local time.
The timezone expression can be:
- A tzinfo struct
- A string description, e.g. "US/Pacific", or "Europe/Berlin"
- An ISO-8601 string, e.g. "+07:00"
- A special string, one of: "local", "utc", or "UTC"
Usage::
>>> import arrow
>>> arrow.now()
<Arrow [2013-05-07T22:19:11.363410-07:00]>
>>> arrow.now('US/Pacific')
<Arrow [2013-05-07T22:19:15.251821-07:00]>
>>> arrow.now('+02:00')
<Arrow [2013-05-08T07:19:25.618646+02:00]>
>>> arrow.now('local')
<Arrow [2013-05-07T22:19:39.130059-07:00]>
'''
if tz is None:
tz = dateutil_tz.tzlocal()
elif not isinstance(tz, tzinfo):
tz = parser.TzinfoParser.parse(tz)
return Arrow.now(tz)
示例13: get_uptime
def get_uptime(message):
"""
Get uptime, code reload time and crash counts this session
Usage: uptime
"""
now = Arrow.now()
reply('''{}
Way status:
[ ] Lost
[X] Not lost
Holding on since:
{}
Uptime:
{}
Last code reload:
{}
Code uptime:
{}
Total crashes this session: {}
'''.format(
VERSION_STRING,
uptime.humanize(),
now - uptime,
code_uptime.humanize(),
now - code_uptime,
crash_count
), message)
示例14: run
def run(self, symbol):
uid = self.get_uuid(symbol)
if uid is None:
return
url = 'http://www.newrank.cn/xdnphb/detail/getAccountArticle'
params = {
'uuid': uid,
}
r = self.req_post(url, data=params)
datas = r.json()
try:
infos = datas['value']['lastestArticle']
for info in infos:
source_url = self.parse_url(info.get('url'))
if self.repeat_check(source_url):
continue
title = info.get('title')
wx_id = info.get('account')
author = info.get('author')
post_time = info.get('publicTime')
post_time = Arrow.strptime(post_time, '%Y-%m-%d %H:%M:%S', tzinfo='Asia/Shanghai').timestamp
summary = info.get('summary')
content, img = self.get_content(source_url)
if info.get('imageUrl') is None:
image = img
else:
image = info.get('imageUrl')
self.add_result(title=title, author=author, post_time=post_time, source_name=author,
source_url=source_url, summary=summary, spider_name=self.spider_name,
content=content, image=image, category=self.category, aid=wx_id)
except Exception as e:
self.log.error(e)
示例15: parse
def parse(self, kind, aid, summary):
url = 'http://api.smzdm.com/v1/%s/articles/%s' % (kind, aid)
if self.blf.exist(url):
return
self.blf.add(url)
try:
r = self.req_get(url)
data = r.json().get('data')
title = data.get('article_title')
author = data.get('article_referrals')
post_time = data.get('article_date')
post_time = Arrow.strptime(post_time, '%Y-%m-%d %H:%M:%S', tzinfo='Asia/Shanghai').timestamp
source_url = data.get('article_url')
# summary = data.get('summary')
content = data.get('article_filter_content')
try:
content = self.get_img(BeautifulSoup('<div>%s</div>' % content, 'lxml'), 'src')
except Exception as e:
self.log.exception(e)
image = data.get('article_pic')
# self.add_result(title=title, author=author, post_time=post_time, source_name=self.spider_name,
# source_url=source_url, summary=summary,
# content=content, image=image, category=self.category, aid=kind)
self.add_result(title=title, author=author, post_time=post_time, source_name='什么值得买',
source_url=source_url, summary=summary, spider_name=self.spider_name,
content=content, image=image, category=self.category, aid=kind)
except Exception as e:
self.log.error(e)