本文整理汇总了Python中babel.dates.format_timedelta函数的典型用法代码示例。如果您正苦于以下问题:Python format_timedelta函数的具体用法?Python format_timedelta怎么用?Python format_timedelta使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了format_timedelta函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _format_date
def _format_date(self):
"""
Return this block's date in a human-readable format. If the date
is None, returns the empty string.
"""
if self.date is None:
return ''
locale = to_locale(get_language())
delta = self.date - datetime.now(utc)
try:
relative_date = format_timedelta(delta, locale=locale)
# Babel doesn't have translations for Esperanto, so we get
# a KeyError when testing translations with
# ?preview-lang=eo. This should not happen with any other
# languages. See https://github.com/python-babel/babel/issues/107
except KeyError:
relative_date = format_timedelta(delta)
date_has_passed = delta.days < 0
# Translators: 'absolute' is a date such as "Jan 01,
# 2020". 'relative' is a fuzzy description of the time until
# 'absolute'. For example, 'absolute' might be "Jan 01, 2020",
# and if today were December 5th, 2020, 'relative' would be "1
# month".
date_format = _(u"{relative} ago - {absolute}") if date_has_passed else _(u"in {relative} - {absolute}")
return date_format.format(
relative=relative_date,
absolute=self.date.astimezone(self.time_zone).strftime(self.date_format.encode('utf-8')).decode('utf-8'),
)
示例2: get_context
def get_context(self):
"""Return the template context used to render this summary block."""
date = ''
if self.date is not None:
# Translators: relative_date is a fuzzy description of the
# time from now until absolute_date. For example,
# absolute_date might be "Jan 01, 2020", and if today were
# December 5th, 2020, relative_date would be "1 month".
locale = to_locale(get_language())
try:
relative_date = format_timedelta(self.date - datetime.now(pytz.UTC), locale=locale)
# Babel doesn't have translations for Esperanto, so we get
# a KeyError when testing translations with
# ?preview-lang=eo. This should not happen with any other
# languages. See https://github.com/python-babel/babel/issues/107
except KeyError:
relative_date = format_timedelta(self.date - datetime.now(pytz.UTC))
date = _("in {relative_date} - {absolute_date}").format(
relative_date=relative_date,
absolute_date=self.date.strftime(self.date_format),
)
return {
'title': self.title,
'date': date,
'description': self.description,
'css_class': self.css_class,
'link': self.link,
'link_text': self.link_text,
}
示例3: test_format_narrow
def test_format_narrow(self):
string = dates.format_timedelta(timedelta(hours=1),
locale='en', format='narrow')
self.assertEqual('1h', string)
string = dates.format_timedelta(timedelta(hours=-2),
locale='en', format='narrow')
self.assertEqual('2h', string)
示例4: i_format
def i_format(loc, s, *a, **kw):
if a:
a = list(a)
for c, f in [(a, enumerate), (kw, dict.items)]:
for k, o in f(c):
o, wrapper = (o.value, o.wrapper) if isinstance(o, Wrap) else (o, None)
if isinstance(o, text_type):
pass
elif isinstance(o, Decimal):
c[k] = format_decimal(o, locale=loc)
elif isinstance(o, int):
c[k] = format_number(o, locale=loc)
elif isinstance(o, Money):
c[k] = loc.format_money(o)
elif isinstance(o, MoneyBasket):
c[k] = loc.format_money_basket(o)
elif isinstance(o, Age):
c[k] = format_timedelta(o, locale=loc, **o.format_args)
elif isinstance(o, timedelta):
c[k] = format_timedelta(o, locale=loc)
elif isinstance(o, datetime):
c[k] = format_datetime(o, locale=loc)
elif isinstance(o, date):
c[k] = format_date(o, locale=loc)
elif isinstance(o, Locale):
c[k] = loc.languages.get(o.language) or o.language.upper()
elif isinstance(o, Currency):
c[k] = loc.currencies.get(o, o)
if wrapper:
c[k] = wrapper % (c[k],)
return s.format(*a, **kw)
示例5: test_small_value_with_granularity
def test_small_value_with_granularity(self):
string = dates.format_timedelta(timedelta(seconds=42),
granularity='hour', locale='en')
self.assertEqual('1 hour', string)
string = dates.format_timedelta(timedelta(seconds=42),
granularity='hour', locale='en',
format='short')
self.assertEqual('1 hr', string)
示例6: _release_threshold_select
def _release_threshold_select(self):
return {0: "Don't ignore.",
1: format_timedelta(helper.releaseThresholdDelta[1], locale=common.getLocale()),
2: format_timedelta(helper.releaseThresholdDelta[2], locale=common.getLocale()),
3: format_timedelta(helper.releaseThresholdDelta[3], locale=common.getLocale()),
4: format_timedelta(helper.releaseThresholdDelta[4], locale=common.getLocale()),
5: format_timedelta(helper.releaseThresholdDelta[5], locale=common.getLocale()),
6: 'Completely ignore'}
示例7: test_direction_adding
def test_direction_adding(self):
string = dates.format_timedelta(timedelta(hours=1),
locale='en',
add_direction=True)
self.assertEqual('in 1 hour', string)
string = dates.format_timedelta(timedelta(hours=-1),
locale='en',
add_direction=True)
self.assertEqual('1 hour ago', string)
示例8: timedelta2
def timedelta2(self, seconds, **kwargs):
for (i, (nm, tm)) in enumerate(TIMEDELTA_UNITS):
if tm < seconds:
result = format_timedelta(seconds, threshold=1, locale=self, **kwargs)
smaller_tm = seconds % tm
not_last = i < len(TIMEDELTA_UNITS) - 1
if not_last and smaller_tm > TIMEDELTA_UNITS[i+1][1]:
result += ' ' + self.format.timedelta(smaller_tm, threshold=1, **kwargs)
return result
return format_timedelta(seconds, locale=self, **kwargs)
示例9: _release_threshold_select
def _release_threshold_select(self):
_local = common.getLocale()
return {
0: "Don't ignore.",
1: format_timedelta(self._releaseThresholdDelta[1], locale=_local),
2: format_timedelta(self._releaseThresholdDelta[2], locale=_local),
3: format_timedelta(self._releaseThresholdDelta[3], locale=_local),
4: format_timedelta(self._releaseThresholdDelta[4], locale=_local),
5: format_timedelta(self._releaseThresholdDelta[5], locale=_local),
6: "Completely ignore",
}
示例10: test_zero_seconds
def test_zero_seconds(self):
string = dates.format_timedelta(timedelta(seconds=0), locale='en')
self.assertEqual('0 seconds', string)
string = dates.format_timedelta(timedelta(seconds=0), locale='en',
format='short')
self.assertEqual('0 sec', string)
string = dates.format_timedelta(timedelta(seconds=0),
granularity='hour', locale='en')
self.assertEqual('0 hours', string)
string = dates.format_timedelta(timedelta(seconds=0),
granularity='hour', locale='en',
format='short')
self.assertEqual('0 hr', string)
示例11: update
def update(self):
self.news = feedparser.parse(self.feed_url)
article_list = []
xlocale = locale.getlocale(locale.LC_TIME)
locale.setlocale(locale.LC_TIME, 'en_US.utf-8')
if not self.news['items']:
Logger.error('NEWS: Seems there\'s no news')
return # Return here so we keep old news (if any)
for x in self.news['items']:
description = unicode(x['description']).strip()
description = description.split('<', 1)[0].strip()
title = unicode(x['title']).strip()
if description == '.':
title = u'[color=#FFDD63]{}[/color]'.format(title)
description = ''
article_date = (datetime.strptime(x['published'], "%a, %d %b %Y %H:%M:%S %Z") + timedelta(hours=2))
article_relative_date = format_timedelta(article_date - datetime.now(),
granularity='minute',
locale='ro_RO.utf-8',
add_direction=True)
article_list.append(u'{}\n[color=#777777]{}[/color]\n\n{}'.format(title,
article_relative_date,
description))
locale.setlocale(locale.LC_TIME, xlocale)
self.articles = deque(article_list)
示例12: show
def show(self, index):
self.print_short(index)
data = []
data.append('Added by ' + Reviewer.get(self.by).nice())
relative = format_timedelta(
datetime.datetime.now(pytz.utc) - self.created
)
data.append(TERM.bold_magenta(' {0} ago'.format(relative)))
data.append('\n\n')
data.append(self.body.strip())
data.append('\n\n')
scores = []
for email, score in self.reviewers.items():
scores.append(
Reviewer.get(email).nice() +
TERM.bright_black(': ')
)
if score >= 1:
fun = TERM.bold_green
score = '+{0}'.format(score)
elif score == 0:
fun = TERM.bold_white
else:
fun = TERM.bold_red
scores.append(fun(str(score)))
scores.append('\n')
data.append(''.join(scores))
print(''.join(data))
示例13: timedelta_filter
def timedelta_filter(delta_or_date):
"""Format :class:`~datetime.datetime` or :class:`~datetime.timedelta`
into localized string.
If given parameter is a :class:`~datetime.datetime`,
it will be subtracted by :func:`railgun.common.dateutil.utcnow` to
get the :class:`~datetime.timedelta`.
Usage:
.. code-block:: html
{{ handin.get_ctime() | timedelta }}
:param delta_or_date: A :class:`~datetime.datetime` or a
:class:`~datetime.timedelta` object.
:return: :data:`None` if `delta_or_date` is :data:`None`, otherwise the
localized timedelta string.
"""
if not delta_or_date:
return None
if isinstance(delta_or_date, datetime):
delta_or_date = delta_or_date - g.utcnow
return format_timedelta(delta_or_date, locale=get_locale())
示例14: time_localed
def time_localed(time, member):
delta = time - datetime.datetime.now()
if member:
locale = member.native_lang
else:
locale = 'en'
return format_timedelta(delta, locale=locale)
示例15: serialize_content_for_general_list
def serialize_content_for_general_list(content: Content, context: Context):
content_type = ContentType(content.type)
last_activity_date = content.get_last_activity_date()
last_activity_date_formatted = format_datetime(last_activity_date,
locale=tg.i18n.get_lang()[0])
last_activity_label = format_timedelta(
datetime.utcnow() - last_activity_date,
locale=tg.i18n.get_lang()[0],
)
last_activity_label = last_activity_label.replace(' ', '\u00A0') # espace insécable
return DictLikeClass(
id=content.content_id,
folder = DictLikeClass({'id': content.parent_id}) if content.parent else None,
workspace=context.toDict(content.workspace) if content.workspace else None,
label=content.get_label(),
url=ContentType.fill_url(content),
type=DictLikeClass(content_type.toDict()),
status=context.toDict(content.get_status()),
is_deleted=content.is_deleted,
is_archived=content.is_archived,
is_editable=content.is_editable,
last_activity = DictLikeClass({'date': last_activity_date,
'label': last_activity_date_formatted,
'delta': last_activity_label})
)