本文整理汇总了Python中babel.dates.format_timedelta函数的典型用法代码示例。如果您正苦于以下问题:Python format_timedelta函数的具体用法?Python format_timedelta怎么用?Python format_timedelta使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了format_timedelta函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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'),
)
开发者ID:CraftAcademy,项目名称:edx-platform,代码行数:28,代码来源:date_summary.py
示例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,
}
开发者ID:ahmadiga,项目名称:min_edx,代码行数:29,代码来源:date_summary.py
示例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)
开发者ID:python-babel,项目名称:babel,代码行数:7,代码来源:test_dates.py
示例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)
开发者ID:devmiyax,项目名称:liberapay.com,代码行数:31,代码来源:i18n.py
示例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)
开发者ID:python-babel,项目名称:babel,代码行数:8,代码来源:test_dates.py
示例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'}
开发者ID:foXaCe,项目名称:XDM,代码行数:8,代码来源:bases.py
示例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)
开发者ID:python-babel,项目名称:babel,代码行数:9,代码来源:test_dates.py
示例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)
开发者ID:SmartTeleMax,项目名称:iktomi-cms-demo,代码行数:10,代码来源:lang.py
示例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",
}
开发者ID:jalons,项目名称:XDM-main-plugin-repo,代码行数:11,代码来源:ReleaseDate.py
示例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)
开发者ID:python-babel,项目名称:babel,代码行数:13,代码来源:test_dates.py
示例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)
开发者ID:talpah,项目名称:pivystation,代码行数:29,代码来源:mediafax.py
示例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))
开发者ID:thiderman,项目名称:git-codereview,代码行数:35,代码来源:review.py
示例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())
开发者ID:heyLinsir,项目名称:railgun,代码行数:25,代码来源:jinja_filters.py
示例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)
开发者ID:eavae,项目名称:mlang,代码行数:7,代码来源:db.py
示例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})
)
开发者ID:lebouquetin,项目名称:tracim,代码行数:27,代码来源:serializers.py
示例16: format_timedelta
def format_timedelta(datetime_or_timedelta, granularity="second"):
"""Format the elapsed time from the given date to now of the given
timedelta.
"""
if isinstance(datetime_or_timedelta, datetime):
datetime_or_timedelta = datetime.utcnow() - datetime_or_timedelta
return dates.format_timedelta(datetime_or_timedelta, granularity, locale=get_locale())
开发者ID:avacariu,项目名称:zine,代码行数:7,代码来源:__init__.py
示例17: format_timedelta
def format_timedelta(self, datetime_or_timedelta, granularity='second',
threshold=.85):
"""Formats the elapsed time from the given date to now or the given
timedelta. This currently requires an unreleased development version
of Babel.
:param datetime_or_timedelta:
A ``timedelta`` object representing the time difference to format,
or a ``datetime`` object in UTC.
:param granularity:
Determines the smallest unit that should be displayed, the value
can be one of "year", "month", "week", "day", "hour", "minute" or
"second".
:param threshold:
Factor that determines at which point the presentation switches to
the next higher unit.
:returns:
A string with the elapsed time.
"""
if isinstance(datetime_or_timedelta, datetime.datetime):
datetime_or_timedelta = datetime.datetime.utcnow() - \
datetime_or_timedelta
return dates.format_timedelta(datetime_or_timedelta, granularity,
threshold=threshold,
locale=self.locale)
开发者ID:404minds,项目名称:quiz-forest,代码行数:26,代码来源:i18n.py
示例18: humanize
def humanize(obj, type=None, length=None):
if obj is None:
obj = ''
elif type and type.startswith('time'):
tz = type[len('time'):].lstrip('-')
tz = timezone(tz) if tz else current_app.timezone or utc
obj = format_time(float(obj), tz) if obj else ''
elif type and type.startswith('natural-time'):
tz = type[len('natural-time'):].lstrip('-')
tz = timezone(tz) if tz else current_app.timezone or utc
delta = datetime.now(tz) - datetime.fromtimestamp(float(obj), tz)
if delta < timedelta(days=1):
obj = format_timedelta(delta, locale='en_US') + ' ago'
else:
obj = format_time(float(obj), tz) if obj else ''
elif isinstance(obj, string_types) and not re.match(UUID_REGEX, obj):
obj = obj.replace('-', ' ').replace('_', ' ')
obj = re.sub('|'.join(KEYWORDS_UP),
lambda m: m.group(0).upper(), obj)
if obj and obj not in KEYWORDS_DOWN:
obj = obj[0].upper() + obj[1:]
elif isinstance(obj, list):
if all(isinstance(x, (int, float) + string_types) for x in obj):
obj = ', '.join(map(str, obj))
if length is not None and len(obj) > length:
obj = obj[:length - 4] + ' ...'
return obj
开发者ID:117111302,项目名称:flower,代码行数:27,代码来源:template.py
示例19: test_format_timedelta
def test_format_timedelta():
assert (dates.format_timedelta(timedelta(weeks=12), locale='en_US')
== u'3 months')
assert (dates.format_timedelta(timedelta(seconds=1), locale='es')
== u'1 segundo')
assert (dates.format_timedelta(timedelta(hours=3), granularity='day',
locale='en_US')
== u'1 day')
assert (dates.format_timedelta(timedelta(hours=23), threshold=0.9,
locale='en_US')
== u'1 day')
assert (dates.format_timedelta(timedelta(hours=23), threshold=1.1,
locale='en_US')
== u'23 hours')
开发者ID:python-babel,项目名称:babel,代码行数:16,代码来源:test_dates.py
示例20: reltime
def reltime(date):
if date == common.FAKEDATE or not date:
return "unknown"
# FIXME use isinstance() ... but test it
if type(date).__name__ not in ('date', 'datetime'):
return "reltime needs a date or datetime we got: '%s'" % repr(date)
return format_timedelta(date - datetime.now(), locale=common.getLocale(), add_direction=True)
开发者ID:Enjoy14,项目名称:XDM,代码行数:7,代码来源:helper.py
注:本文中的babel.dates.format_timedelta函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论