def time_since(d, now=None): if not isinstance(d, datetime.datetime): d = datetime.datetime(d.year, d.month, d.day) if now and not isinstance(now, datetime.datetime): now = datetime.datetime(now.year, now.month, now.day) if not now: now = datetime.datetime.now(utc if is_aware(d) else None) delta = now - d leapdays = calendar.leapdays(d.year, now.year) if leapdays != 0: if calendar.isleap(d.year): leapdays -= 1 elif calendar.isleap(now.year): leapdays += 1 delta -= datetime.timedelta(leapdays) since = delta.days * 24 * 60 * 60 + delta.seconds if since <= 0: return avoid_wrapping(ugettext('0'+u'分钟前')) x = 0 seconds = 0 name = "" count = 1 for x, (seconds, name) in enumerate(TIMESINCE_CHUNKS): count = since // seconds if count != 0: break result = avoid_wrapping(name % count) if x + 1 < len(TIMESINCE_CHUNKS): seconds2, name2 = TIMESINCE_CHUNKS[x + 1] count2 = (since - (seconds * count)) // seconds2 if count2 != 0: result += ugettext(', ') + avoid_wrapping(name2 % count2) return result
def mytimesince(d, now=None, reversed=False): """ Takes two datetime objects and returns the time between d and now as a nicely formatted string, e.g. "10 minutes". If d occurs after now, then "0 minutes" is returned. Units used are years, months, weeks, days, hours, and minutes. Seconds and microseconds are ignored. Up to two adjacent units will be displayed. For example, "2 weeks, 3 days" and "1 year, 3 months" are possible outputs, but "2 weeks, 3 hours" and "1 year, 5 days" are not. Adapted from http://web.archive.org/web/20060617175230/http://blog.natbat.co.uk/archive/2003/Jun/14/time_since """ # Convert datetime.date to datetime.datetime for comparison. if not isinstance(d, datetime.datetime): d = datetime.datetime(d.year, d.month, d.day) if now and not isinstance(now, datetime.datetime): now = datetime.datetime(now.year, now.month, now.day) if not now: now = datetime.datetime.now(utc if is_aware(d) else None) delta = (d - now) if reversed else (now - d) # ignore microseconds since = delta.days * 24 * 60 * 60 + delta.seconds if since <= 0: # d is in the future compared to now, stop processing. return avoid_wrapping(ugettext('0 minutes')) for i, (seconds, name) in enumerate(TIMESINCE_CHUNKS): count = since // seconds if count != 0: break result = avoid_wrapping(name % count) return result
def filesizeformat(bytes): """ Formats the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102 bytes, etc). """ try: bytes = float(bytes) except (TypeError, ValueError, UnicodeDecodeError): value = ungettext("%(size)d byte", "%(size)d bytes", 0) % {'size': 0} return avoid_wrapping(value) filesize_number_format = lambda value: formats.number_format(round(value, 1), 1) KB = 1 << 10 MB = 1 << 20 GB = 1 << 30 TB = 1 << 40 PB = 1 << 50 if bytes < KB: value = ungettext("%(size)d byte", "%(size)d bytes", bytes) % {'size': bytes} elif bytes < MB: value = ugettext("%s KB") % filesize_number_format(bytes / KB) elif bytes < GB: value = ugettext("%s MB") % filesize_number_format(bytes / MB) elif bytes < TB: value = ugettext("%s GB") % filesize_number_format(bytes / GB) elif bytes < PB: value = ugettext("%s TB") % filesize_number_format(bytes / TB) else: value = ugettext("%s PB") % filesize_number_format(bytes / PB) return avoid_wrapping(value)
def bwformat(bps): try: bps = float(bps) except (TypeError, ValueError, UnicodeDecodeError): value = ungettext("%(bw)d bps", "%(bw)d bps", 0) % {'bw': 0} return avoid_wrapping(value) filesize_number_format = lambda value: formats.number_format(round(value, 1), -1) K = 1 * 10 ** 3 M = 1 * 10 ** 6 G = 1 * 10 ** 9 T = 1 * 10 ** 12 P = 1 * 10 ** 15 if bps < K: value = ungettext("%(size)d bps", "%(size)d bps", bps) % {'size': bps} elif bps < M: value = ugettext("%s Kbps") % filesize_number_format(bps / K) elif bps < G: value = ugettext("%s Mbps") % filesize_number_format(bps / M) elif bps < T: value = ugettext("%s Gbps") % filesize_number_format(bps / G) elif bps < P: value = ugettext("%s Tbps") % filesize_number_format(bps / T) else: value = ugettext("%s Pbps") % filesize_number_format(bps / P) return avoid_wrapping(value)
def filesizeformat(bytes): """ Formats the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102 bytes, etc.). """ try: bytes = float(bytes) except (TypeError, ValueError, UnicodeDecodeError): value = ungettext("%(size)d byte", "%(size)d bytes", 0) % {'size': 0} return avoid_wrapping(value) filesize_number_format = lambda value: formats.number_format(round(value, 1), 1) KB = 1 << 10 MB = 1 << 20 GB = 1 << 30 TB = 1 << 40 PB = 1 << 50 if bytes < KB: value = ungettext("%(size)d byte", "%(size)d bytes", bytes) % {'size': bytes} elif bytes < MB: value = ugettext("%s KB") % filesize_number_format(bytes / KB) elif bytes < GB: value = ugettext("%s MB") % filesize_number_format(bytes / MB) elif bytes < TB: value = ugettext("%s GB") % filesize_number_format(bytes / GB) elif bytes < PB: value = ugettext("%s TB") % filesize_number_format(bytes / TB) else: value = ugettext("%s PB") % filesize_number_format(bytes / PB) return avoid_wrapping(value)
def timesince(d, now=None, reversed=False, time_strings=None): """ Take two datetime objects and return the time between d and now as a nicely formatted string, e.g. "10 minutes". If d occurs after now, return "0 minutes". Units used are years, months, weeks, days, hours, and minutes. Seconds and microseconds are ignored. Up to two adjacent units will be displayed. For example, "2 weeks, 3 days" and "1 year, 3 months" are possible outputs, but "2 weeks, 3 hours" and "1 year, 5 days" are not. `time_strings` is an optional dict of strings to replace the default TIME_STRINGS dict. Adapted from https://web.archive.org/web/20060617175230/http://blog.natbat.co.uk/archive/2003/Jun/14/time_since """ if time_strings is None: time_strings = TIME_STRINGS # Convert datetime.date to datetime.datetime for comparison. if not isinstance(d, datetime.datetime): d = datetime.datetime(d.year, d.month, d.day) if now and not isinstance(now, datetime.datetime): now = datetime.datetime(now.year, now.month, now.day) now = now or datetime.datetime.now(utc if is_aware(d) else None) if reversed: d, now = now, d delta = now - d # Deal with leapyears by subtracing the number of leapdays leapdays = calendar.leapdays(d.year, now.year) if leapdays != 0: if calendar.isleap(d.year): leapdays -= 1 elif calendar.isleap(now.year): leapdays += 1 delta -= datetime.timedelta(leapdays) # ignore microseconds since = delta.days * 24 * 60 * 60 + delta.seconds if since <= 0: # d is in the future compared to now, stop processing. return avoid_wrapping(time_strings["minute"] % 0) for i, (seconds, name) in enumerate(TIMESINCE_CHUNKS): count = since // seconds if count != 0: break result = avoid_wrapping(time_strings[name] % count) if i + 1 < len(TIMESINCE_CHUNKS): # Now get the second item seconds2, name2 = TIMESINCE_CHUNKS[i + 1] count2 = (since - (seconds * count)) // seconds2 if count2 != 0: result += gettext(", ") + avoid_wrapping( time_strings[name2] % count2) return result
def timesince(d, now=None, reversed=False, time_strings=None): """ Take two datetime objects and return the time between d and now as a nicely formatted string, e.g. "10 minutes". If d occurs after now, return "0 minutes". Units used are years, months, weeks, days, hours, and minutes. Seconds and microseconds are ignored. Up to two adjacent units will be displayed. For example, "2 weeks, 3 days" and "1 year, 3 months" are possible outputs, but "2 weeks, 3 hours" and "1 year, 5 days" are not. `time_strings` is an optional dict of strings to replace the default TIME_STRINGS dict. Adapted from http://web.archive.org/web/20060617175230/http://blog.natbat.co.uk/archive/2003/Jun/14/time_since """ if time_strings is None: time_strings = TIME_STRINGS # Convert datetime.date to datetime.datetime for comparison. if not isinstance(d, datetime.datetime): d = datetime.datetime(d.year, d.month, d.day) if now and not isinstance(now, datetime.datetime): now = datetime.datetime(now.year, now.month, now.day) now = now or datetime.datetime.now(utc if is_aware(d) else None) if reversed: d, now = now, d delta = now - d # Deal with leapyears by subtracing the number of leapdays leapdays = calendar.leapdays(d.year, now.year) if leapdays != 0: if calendar.isleap(d.year): leapdays -= 1 elif calendar.isleap(now.year): leapdays += 1 delta -= datetime.timedelta(leapdays) # ignore microseconds since = delta.days * 24 * 60 * 60 + delta.seconds if since <= 0: # d is in the future compared to now, stop processing. return avoid_wrapping(gettext('0 minutes')) for i, (seconds, name) in enumerate(TIMESINCE_CHUNKS): count = since // seconds if count != 0: break result = avoid_wrapping(time_strings[name] % count) if i + 1 < len(TIMESINCE_CHUNKS): # Now get the second item seconds2, name2 = TIMESINCE_CHUNKS[i + 1] count2 = (since - (seconds * count)) // seconds2 if count2 != 0: result += gettext(', ') + avoid_wrapping(time_strings[name2] % count2) return result
def timesincehumanize(d, now=None, reversed=False): """ Takes two datetime objects and returns the time between d and now as a nicely formatted string, e.g. "10 minutes". If d occurs after now, then "Just now" is returned. Units used are years, months, weeks, days, hours, and minutes. Seconds and microseconds are ignored. Up to one unit will be displayed. For example, "2 weeks" and "1 year" are possible outputs, but "2 weeks, 3 hours" and "1 year, 5 days" are not. Adapted from http://web.archive.org/web/20060617175230/http://blog.natbat.co.uk/archive/2003/Jun/14/time_since """ # Convert datetime.date to datetime.datetime for comparison. if not isinstance(d, datetime.datetime): d = datetime.datetime(d.year, d.month, d.day) if now and not isinstance(now, datetime.datetime): now = datetime.datetime(now.year, now.month, now.day) if not now: now = datetime.datetime.now(utc if is_aware(d) else None) if reversed: d, now = now, d delta = now - d # Deal with leapyears by subtracing the number of leapdays leapdays = calendar.leapdays(d.year, now.year) if leapdays != 0: if calendar.isleap(d.year): leapdays -= 1 elif calendar.isleap(now.year): leapdays += 1 delta -= datetime.timedelta(leapdays) # ignore microseconds since = delta.days * 24 * 60 * 60 + delta.seconds if since <= 0: # d is in the future compared to now, stop processing. return avoid_wrapping(ugettext('Just now')) for i, (seconds, name) in enumerate(TIMESINCE_CHUNKS): count = since // seconds if count != 0: break result = avoid_wrapping(name % count) + (' ago') """ if i + 1 < len(TIMESINCE_CHUNKS): # Now get the second item seconds2, name2 = TIMESINCE_CHUNKS[i + 1] count2 = (since - (seconds * count)) // seconds2 if count2 != 0: result += ugettext(', ') + avoid_wrapping(name2 % count2) """ return result
def percentageformat(value): """ Formats the float value to percentage like 14.02% 22.19% etc). """ p = '' try: value = float(value) except (TypeError, ValueError, UnicodeDecodeError): return avoid_wrapping(value) p = '%.2f%%' %(value*100) return avoid_wrapping(p)
def percentageformat(value): """ Formats the float value to percentage like 14.02% 22.19% etc). """ p = '' try: value = float(value) except (TypeError, ValueError, UnicodeDecodeError): return avoid_wrapping(value) p = '%.2f%%' % (value * 100) return avoid_wrapping(p)
def rutimesince(d, now=None, reversed=False): """ Takes two datetime objects and returns the time between d and now as a nicely formatted string, e.g. "10 minutes". If d occurs after now, then "0 minutes" is returned. Units used are years, months, weeks, days, hours, and minutes. Seconds and microseconds are ignored. Up to two adjacent units will be displayed. For example, "2 weeks, 3 days" and "1 year, 3 months" are possible outputs, but "2 weeks, 3 hours" and "1 year, 5 days" are not. Adapted from http://web.archive.org/web/20060617175230/http://blog.natbat.co.uk/archive/2003/Jun/14/time_since """ chunks = ( (60 * 60 * 24 * 365, ('%d год', '%d года', '%d лет')), (60 * 60 * 24 * 30, ('%d месяц', '%d месяц', '%d месяцев')), (60 * 60 * 24 * 7, ('%d неделя', '%d недели', '%d недель')), (60 * 60 * 24, ('%d день', '%d дня', '%d дней')), (60 * 60, ('%d час', '%d часа', '%d часов')), (60, ('%d минута', '%d минуты', '%d минут')) ) # Convert datetime.date to datetime.datetime for comparison. if not isinstance(d, datetime.datetime): d = datetime.datetime(d.year, d.month, d.day) if now and not isinstance(now, datetime.datetime): now = datetime.datetime(now.year, now.month, now.day) if not now: now = datetime.datetime.now(utc if is_aware(d) else None) delta = (d - now) if reversed else (now - d) # ignore microseconds since = delta.days * 24 * 60 * 60 + delta.seconds if since <= 0: # d is in the future compared to now, stop processing. return avoid_wrapping(ugettext('0 minutes')) for i, (seconds, names) in enumerate(chunks): count = since // seconds name = get_rus_name_for_number(count, names) if count != 0: break result = avoid_wrapping(name % count) if i + 1 < len(chunks): # Now get the second item seconds2, names2 = chunks[i + 1] count2 = (since - (seconds * count)) // seconds2 name2 = get_rus_name_for_number(count2, names2) if count2 != 0: result += avoid_wrapping(', ') + avoid_wrapping(name2 % count2) return result
def timesince(d, now=None, reversed=False): """ Takes two datetime objects and returns the time between d and now as a nicely formatted string, e.g. "10 minutes". If d occurs after now, then "0 minutes" is returned. Units used are years, months, weeks, days, hours, and minutes. Seconds and microseconds are ignored. Up to two adjacent units will be displayed. For example, "2 weeks, 3 days" and "1 year, 3 months" are possible outputs, but "2 weeks, 3 hours" and "1 year, 5 days" are not. Adapted from http://web.archive.org/web/20060617175230/http://blog.natbat.co.uk/archive/2003/Jun/14/time_since """ chunks = ( (60 * 60 * 24 * 365, ungettext_lazy("%d year", "%d years")), (60 * 60 * 24 * 30, ungettext_lazy("%d month", "%d months")), (60 * 60 * 24 * 7, ungettext_lazy("%d week", "%d weeks")), (60 * 60 * 24, ungettext_lazy("%d day", "%d days")), (60 * 60, ungettext_lazy("%d hour", "%d hours")), (60, ungettext_lazy("%d minute", "%d minutes")), ) # Convert datetime.date to datetime.datetime for comparison. if not isinstance(d, datetime.datetime): d = datetime.datetime(d.year, d.month, d.day) if now and not isinstance(now, datetime.datetime): now = datetime.datetime(now.year, now.month, now.day) if not now: now = datetime.datetime.now(utc if is_aware(d) else None) delta = (d - now) if reversed else (now - d) # ignore microseconds since = delta.days * 24 * 60 * 60 + delta.seconds if since <= 0: # d is in the future compared to now, stop processing. return avoid_wrapping(ugettext("0 minutes")) for i, (seconds, name) in enumerate(chunks): count = since // seconds if count != 0: break result = avoid_wrapping(name % count) if count <= 1 and i + 1 < len(chunks): # Now get the second item seconds2, name2 = chunks[i + 1] count2 = (since - (seconds * count)) // seconds2 if count2 != 0: result += ugettext(", ") + avoid_wrapping(name2 % count2) return result
def timesince(d, now=None, reversed=False): """ Takes two datetime objects and returns the time between d and now as a nicely formatted string, e.g. "10 minutes". If d occurs after now, then "0 minutes" is returned. Units used are years, months, weeks, days, hours, and minutes. Seconds and microseconds are ignored. Up to two adjacent units will be displayed. For example, "2 weeks, 3 days" and "1 year, 3 months" are possible outputs, but "2 weeks, 3 hours" and "1 year, 5 days" are not. Adapted from http://web.archive.org/web/20060617175230/http://blog.natbat.co.uk/archive/2003/Jun/14/time_since """ chunks = ( (60 * 60 * 24 * 365, ungettext_lazy('%d year', '%d years')), (60 * 60 * 24 * 30, ungettext_lazy('%d month', '%d months')), (60 * 60 * 24 * 7, ungettext_lazy('%d week', '%d weeks')), (60 * 60 * 24, ungettext_lazy('%d day', '%d days')), (60 * 60, ungettext_lazy('%d hour', '%d hours')), (60, ungettext_lazy('%d minute', '%d minutes')) ) # Convert datetime.date to datetime.datetime for comparison. if not isinstance(d, datetime.datetime): d = datetime.datetime(d.year, d.month, d.day) if now and not isinstance(now, datetime.datetime): now = datetime.datetime(now.year, now.month, now.day) if not now: now = datetime.datetime.now(utc if is_aware(d) else None) delta = (d - now) if reversed else (now - d) # ignore microseconds since = delta.days * 24 * 60 * 60 + delta.seconds if since <= 0: # d is in the future compared to now, stop processing. return avoid_wrapping(ugettext('0 minutes')) for i, (seconds, name) in enumerate(chunks): count = since // seconds if count != 0: break result = avoid_wrapping(name % count) if count <= 1 and i + 1 < len(chunks): # Now get the second item seconds2, name2 = chunks[i + 1] count2 = (since - (seconds * count)) // seconds2 if count2 != 0: result += ugettext(', ') + avoid_wrapping(name2 % count2) return result
def timesince2(d, now=None, reversed=False): import datetime from django.utils.html import avoid_wrapping from django.utils.timezone import is_aware, utc from django.utils.translation import ugettext, ungettext_lazy chunks = ( (60 * 60 * 24 * 365, ungettext_lazy('%d year', '%d years')), (60 * 60 * 24 * 30, ungettext_lazy('%d month', '%d months')), (60 * 60 * 24 * 7, ungettext_lazy('%d week', '%d weeks')), (60 * 60 * 24, ungettext_lazy('%d day', '%d days')), (60 * 60, ungettext_lazy('%d hour', '%d hours')), (60, ungettext_lazy('%d minute', '%d minutes')) ) # Convert datetime.date to datetime.datetime for comparison. if not isinstance(d, datetime.datetime): d = datetime.datetime(d.year, d.month, d.day) if now and not isinstance(now, datetime.datetime): now = datetime.datetime(now.year, now.month, now.day) if not now: now = datetime.datetime.now(utc if is_aware(d) else None) delta = (d - now) if reversed else (now - d) # ignore microseconds since = delta.days * 24 * 60 * 60 + delta.seconds if since == 0: return "Today" if since == 86400: return "Tomorrow" if since <= 0: # d is in the future compared to now, stop processing. return avoid_wrapping(ugettext('0 minutes')) for i, (seconds, name) in enumerate(chunks): count = since // seconds if count != 0: break result = avoid_wrapping(name % count) if i + 1 < len(chunks): # Now get the second item seconds2, name2 = chunks[i + 1] count2 = (since - (seconds * count)) // seconds2 if count2 != 0: result += ugettext(', ') + avoid_wrapping(name2 % count2) return result
def percentageformat(value, base): """ Formats the result of divide value by base to percentage like 14.02% 22.19% etc). """ if isinstance(value, int) and value == 0: return avoid_wrapping('0.00%') if value is None or not base: return avoid_wrapping(f'{value}/{base}') try: p = f'{(value / base)*100 :.2f}%' except Exception: return avoid_wrapping(f'{value}/{base}') return avoid_wrapping(p)
def filesizeformat_persian(bytes): try: filesize_number_format = lambda value: formats.number_format( round(value, 1), 1) KB = 1 << 10 MB = 1 << 20 GB = 1 << 30 TB = 1 << 40 PB = 1 << 50 if bytes < KB: value = "%s بایت" % filesize_number_format(bytes / KB) elif bytes < MB: value = "%s کیلوبایت" % filesize_number_format(bytes / KB) elif bytes < GB: value = "%s مگابایت" % filesize_number_format(bytes / MB) elif bytes < TB: value = "%s گیگابایت" % filesize_number_format(bytes / GB) elif bytes < PB: value = "%s ترابایت" % filesize_number_format(bytes / TB) else: value = "%s پنتابایت" % filesize_number_format(bytes / PB) return avoid_wrapping(value) except: return 0
def bytesdetailformat(bytes): def _format_size(bytes, callback): bytes = float(bytes) KB = 1 << 10 MB = 1 << 20 GB = 1 << 30 TB = 1 << 40 PB = 1 << 50 if bytes < KB: return callback('', bytes) elif bytes < MB: return callback('K', bytes / KB) elif bytes < GB: return callback('M', bytes / MB) elif bytes < TB: return callback('G', bytes / GB) elif bytes < PB: return callback('T', bytes / TB) else: return callback('P', bytes / PB) return avoid_wrapping( _format_size(bytes * 1024, lambda x, y: ['%d %sB', '%.2f %sB'][bool(x)] % (y, x)))
def human_timedelta(t): """ Converts a time duration into a friendly text representation. (`X ms`, `sec`, `minutes` etc.) >>> human_timedelta(datetime.timedelta(microseconds=1000)) '1.0\xa0ms' >>> human_timedelta(0.01) '10.0\xa0ms' >>> human_timedelta(0.9) '900.0\xa0ms' >>> human_timedelta(datetime.timedelta(seconds=1)) '1.0\xa0seconds' >>> human_timedelta(65.5) '1.1\xa0minutes' >>> human_timedelta(59 * 60) '59.0\xa0minutes' >>> human_timedelta(60*60) '1.0\xa0hours' >>> human_timedelta(1.05*60*60) '1.1\xa0hours' >>> human_timedelta(datetime.timedelta(hours=24)) '1.0\xa0days' >>> human_timedelta(2.54 * 60 * 60 * 24 * 365) '2.5\xa0years' >>> human_timedelta('type error') Traceback (most recent call last): ... TypeError: human_timedelta() argument must be timedelta, integer or float) """ if isinstance(t, datetime.timedelta): t = t.total_seconds() elif not isinstance(t, (int, float)): raise TypeError( 'human_timedelta() argument must be timedelta, integer or float)') if abs(t) < 1: return avoid_wrapping(_('%.1f ms') % round(t * 1000, 1)) if abs(t) < 60: return avoid_wrapping(_('%.1f seconds') % round(t, 1)) for seconds, time_string in TIMESINCE_CHUNKS: count = t / seconds if abs(count) >= 1: count = round(count, 1) break return avoid_wrapping(time_string % count)
def sizeformat(value, arg="B"): """ Formats the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102 bytes, etc). """ try: bytes = float(value) except (TypeError, ValueError, UnicodeDecodeError): value = ungettext("%(size)d byte", "%(size)d bytes", 0) % {'size': 0} return avoid_wrapping(value) filesize_number_format = lambda value: formats.number_format(round(value, 1), 1) KB = 1 << 10 MB = 1 << 20 GB = 1 << 30 TB = 1 << 40 PB = 1 << 50 # 在原函数的基础上,添加了单位参数,使不同量级数据都可以被格式化 switch = { 'KB': KB, 'MB': MB, 'GB': GB, 'TB': TB, 'PB': PB } if arg in switch: bytes *= switch[arg] if bytes < KB: value = ungettext("%(size)d byte", "%(size)d bytes", bytes) % {'size': bytes} elif bytes < MB: value = ugettext("%s KB") % filesize_number_format(bytes / KB) elif bytes < GB: value = ugettext("%s MB") % filesize_number_format(bytes / MB) elif bytes < TB: value = ugettext("%s GB") % filesize_number_format(bytes / GB) elif bytes < PB: value = ugettext("%s TB") % filesize_number_format(bytes / TB) else: value = ugettext("%s PB") % filesize_number_format(bytes / PB) return avoid_wrapping(value)
def sizeformat(bytes, arg="B"): """ Formats the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102 bytes, etc). """ try: bytes = float(bytes) except (TypeError, ValueError, UnicodeDecodeError): value = ungettext("%(size)d byte", "%(size)d bytes", 0) % {'size': 0} return avoid_wrapping(value) filesize_number_format = lambda value: formats.number_format(round(value, 1), 1) KB = 1 << 10 MB = 1 << 20 GB = 1 << 30 TB = 1 << 40 PB = 1 << 50 # 在原函数的基础上,添加了单位参数,使不同量级数据都可以被格式化 switch = { 'KB': KB, 'MB': MB, 'GB': GB, 'TB': TB, 'PB': PB } if arg in switch: bytes *= switch[arg] if bytes < KB: value = ungettext("%(size)d byte", "%(size)d bytes", bytes) % {'size': bytes} elif bytes < MB: value = ugettext("%s KB") % filesize_number_format(bytes / KB) elif bytes < GB: value = ugettext("%s MB") % filesize_number_format(bytes / MB) elif bytes < TB: value = ugettext("%s GB") % filesize_number_format(bytes / GB) elif bytes < PB: value = ugettext("%s TB") % filesize_number_format(bytes / TB) else: value = ugettext("%s PB") % filesize_number_format(bytes / PB) return avoid_wrapping(value)
def naturaltime(d, now=None, time_strings=None, depth=2): if time_strings is None: time_strings = TIME_STRINGS if depth <= 0: raise ValueError('depth must be greater than 0.') # Convert datetime.date to datetime.datetime for comparison. if not isinstance(d, datetime.datetime): d = datetime.datetime(d.year, d.month, d.day) if now and not isinstance(now, datetime.datetime): if isinstance(now, datetime.datetime): raise TypeError('now must be datetime.') else: now = datetime.datetime(now.year, now.month, now.day) now = now or datetime.datetime.now(utc if is_aware(d) else None) if now > d: is_future = False else: is_future = True d, now = now, d delta = now - d # Deal with leapyears by subtracing the number of leapdays leapdays = calendar.leapdays(d.year, now.year) if leapdays != 0: if calendar.isleap(d.year): leapdays -= 1 elif calendar.isleap(now.year): leapdays += 1 delta -= datetime.timedelta(leapdays) # ignore microseconds since = delta.days * 24 * 60 * 60 + delta.seconds result = [] current_depth = 0 i = 0 while i < len(TIMESINCE_CHUNKS) and current_depth < depth: seconds, name = TIMESINCE_CHUNKS[i] count = since // seconds if count == 0: pass else: result.append(avoid_wrapping(time_strings[name] % count)) since -= seconds * count current_depth += 1 i += 1 if len(result) == 0: return _('now') else: delta = _(', ').join(result) if is_future: return time_strings['future-day'] % delta else: return time_strings['past-day'] % delta
def filesizeformat(bytes_): """ Format the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102 bytes, etc.). NOTE: Temporarily here to patch an error raised with Python 3.7+ complaining about bytes_ being a float instead of an int. """ try: bytes_ = int(float(bytes_)) except (TypeError, ValueError, UnicodeDecodeError): value = ngettext("%(size)d byte", "%(size)d bytes", 0) % {'size': 0} return avoid_wrapping(value) def filesize_number_format(value): return formats.number_format(round(value, 1), 1) KB = 1 << 10 MB = 1 << 20 GB = 1 << 30 TB = 1 << 40 PB = 1 << 50 negative = bytes_ < 0 if negative: bytes_ = -bytes_ # Allow formatting of negative numbers. if bytes_ < KB: value = ngettext("%(size)d byte", "%(size)d bytes", bytes_) % {'size': bytes_} elif bytes_ < MB: value = _("%s KB") % filesize_number_format(bytes_ / KB) elif bytes_ < GB: value = _("%s MB") % filesize_number_format(bytes_ / MB) elif bytes_ < TB: value = _("%s GB") % filesize_number_format(bytes_ / GB) elif bytes_ < PB: value = _("%s TB") % filesize_number_format(bytes_ / TB) else: value = _("%s PB") % filesize_number_format(bytes_ / PB) if negative: value = "-%s" % value return avoid_wrapping(value)
def filesizeformat(bytes_): """ Formats the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102 bytes, etc.). """ try: bytes_ = float(bytes_) except (TypeError, ValueError, UnicodeDecodeError): value = ngettext("%(size)d byte", "%(size)d bytes", 0) % {'size': 0} return avoid_wrapping(value) def filesize_number_format(value): return formats.number_format(round(value, 1), 1) KB = 1 << 10 MB = 1 << 20 GB = 1 << 30 TB = 1 << 40 PB = 1 << 50 negative = bytes_ < 0 if negative: bytes_ = -bytes_ # Allow formatting of negative numbers. if bytes_ < KB: value = ngettext("%(size)d byte", "%(size)d bytes", bytes_) % { 'size': bytes_ } elif bytes_ < MB: value = gettext("%s KB") % filesize_number_format(bytes_ / KB) elif bytes_ < GB: value = gettext("%s MB") % filesize_number_format(bytes_ / MB) elif bytes_ < TB: value = gettext("%s GB") % filesize_number_format(bytes_ / GB) elif bytes_ < PB: value = gettext("%s TB") % filesize_number_format(bytes_ / TB) else: value = gettext("%s PB") % filesize_number_format(bytes_ / PB) if negative: value = "-%s" % value return avoid_wrapping(value)
def timediff_filter(value, arg=None): """Combines the functionality of timesince and timeuntil""" if not value: return '' try: if timesince(value, arg) == avoid_wrapping(ugettext('0 minutes')): return 'In ' + timeuntil(value, arg) else: return timesince(value, arg) + ' ago' except (ValueError, TypeError): return ''
def timesince_simple(d): """ Returns a simplified timesince: 19 hours, 48 minutes ago -> 19 hours ago 1 week, 1 day ago -> 1 week ago 0 minutes ago -> just now """ time_period = timesince(d).split(',')[0] if time_period == avoid_wrapping(_('0 minutes')): return _("Just now") return _("%(time_period)s ago") % {'time_period': time_period}
def daysince(d, now=None): """ Takes two datetime objects and returns the days between d and now as a nicely formatted string, e.g. "10 days". If d occurs after now, then "0 days" is returned. """ #Check if now provided if not now: now = datetime.datetime.now(utc if is_aware(d) else None) #Apply local timezone to objects and then zero the time part to include #inconcluded days in the count now = localtime(now).replace(hour=0, minute=0, second=0, microsecond=0) d = localtime(d).replace(hour=0, minute=0, second=0, microsecond=0) #Check for negative delta if d > now: return avoid_wrapping(ugettext('0 days')) delta = now - d return avoid_wrapping(ungettext_lazy('%d day', '%d days') % delta.days)
def naturalduration(value): """ For a timedelta, returns a nicely formatted string, e.g. "10 minutes". Units used are years, months, weeks, days, hours, minutes and seconds. Microseconds are ignored. Up to two adjacent units will be displayed. For example, "2 weeks, 3 days" and "1 year, 3 months" are possible outputs, but "2 weeks, 3 hours" and "1 year, 5 days" are not. Adapted from django's timesince default filter. """ if not isinstance(value, datetime.timedelta): return value chunks = ( (60 * 60 * 24 * 365, ungettext_lazy('%d year', '%d years')), (60 * 60 * 24 * 30, ungettext_lazy('%d month', '%d months')), (60 * 60 * 24 * 7, ungettext_lazy('%d week', '%d weeks')), (60 * 60 * 24, ungettext_lazy('%d day', '%d days')), (60 * 60, ungettext_lazy('%d hour', '%d hours')), (60, ungettext_lazy('%d minute', '%d minutes')), (1, ungettext_lazy('%d second', '%d seconds')) ) # ignore microseconds since = value.days * 24 * 60 * 60 + value.seconds for i, (seconds, name) in enumerate(chunks): count = since // seconds if count != 0: break result = avoid_wrapping(name % count) if i + 1 < len(chunks): # Now get the second item seconds2, name2 = chunks[i + 1] count2 = (since - (seconds * count)) // seconds2 if count2 != 0: result += ugettext(', ') + avoid_wrapping(name2 % count2) return result
def timesince(d, now=None, reversed=False): """ 时刻d距今的秒数,翻译为人类易读的格式. 例如3600秒翻译为"小时",2592000秒翻译为"月" """ chunks = ( (60 * 60 * 24 * 365, '%d年'), (60 * 60 * 24 * 30, '%d月'), (60 * 60 * 24 * 7, '%d周'), (60 * 60 * 24, '%d天'), (60 * 60, '%d小时'), (60, '%d分钟'), ) # Convert date to datetime for comparison. if not isinstance(d, datetime): d = datetime(d.year, d.month, d.day) if now and not isinstance(now, datetime): now = datetime(now.year, now.month, now.day) if not now: now = datetime.now(utc if is_aware(d) else None) delta = (d - now) if reversed else (now - d) # ignore microseconds since = delta.days * 24 * 60 * 60 + delta.seconds if since <= 0: # d is in the future compared to now, stop processing. return avoid_wrapping('0分钟') for i, (seconds, name) in enumerate(chunks): count = since // seconds if count != 0: break result = avoid_wrapping(name % count) if i + 1 < len(chunks): # Now get the second item seconds2, name2 = chunks[i + 1] count2 = (since - (seconds * count)) // seconds2 if count2 != 0: result += avoid_wrapping(name2 % count2) return result
def filesizeformat(bytes_): """ Format the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102 bytes, etc.). """ try: bytes_ = float(bytes_) except (TypeError, ValueError, UnicodeDecodeError): value = ngettext("%(size)d byte", "%(size)d bytes", 0) % {'size': 0} return avoid_wrapping(value) def filesize_number_format(value): return formats.number_format(round(value, 1), 1) KB = 1 << 10 MB = 1 << 20 GB = 1 << 30 TB = 1 << 40 PB = 1 << 50 negative = bytes_ < 0 if negative: bytes_ = -bytes_ # Allow formatting of negative numbers. if bytes_ < KB: value = ngettext("%(size)d byte", "%(size)d bytes", bytes_) % {'size': bytes_} elif bytes_ < MB: value = gettext("%s KB") % filesize_number_format(bytes_ / KB) elif bytes_ < GB: value = gettext("%s MB") % filesize_number_format(bytes_ / MB) elif bytes_ < TB: value = gettext("%s GB") % filesize_number_format(bytes_ / GB) elif bytes_ < PB: value = gettext("%s TB") % filesize_number_format(bytes_ / TB) else: value = gettext("%s PB") % filesize_number_format(bytes_ / PB) if negative: value = "-%s" % value return avoid_wrapping(value)
def bpformat(bp): """ Format the value like a 'human-readable' file size (i.e. 13 Kbp, 4.1 Mbp, 102 bp, etc.). """ try: bp = int(bp) except (TypeError, ValueError, UnicodeDecodeError): return avoid_wrapping("0 bp") def bp_number_format(value): return formats.number_format(round(value, 1), 1) kbp = 1 << 10 mbp = 1 << 20 gbp = 1 << 30 tbp = 1 << 40 pbp = 1 << 50 negative = bp < 0 if negative: bp = -bp # Allow formatting of negative numbers. if bp < kbp: value = "%(size)d byte" % {"size": bp} elif bp < mbp: value = "%s Kbp" % bp_number_format(bp / kbp) elif bp < gbp: value = "%s Mbp" % bp_number_format(bp / mbp) elif bp < tbp: value = "%s Gbp" % bp_number_format(bp / gbp) elif bp < pbp: value = "%s Tbp" % bp_number_format(bp / tbp) else: value = "%s Pbp" % bp_number_format(bp / bp) if negative: value = "-%s" % value return avoid_wrapping(value)
def naturaldate(value): today = timezone.now().date() if value == today: return 'today' else: difference = value - today if difference.days < 7: template = ungettext_lazy('%d day', '%d days') result = avoid_wrapping(template % difference.days) else: result = defaultfilters.timeuntil(value) return pgettext('naturaltime', result)
def formatduration(seconds): if seconds is None: return "" parts = [] if seconds >= 60: minutes = seconds / 60 if seconds >= 60 * 60: hours = seconds / 3600 minutes = (seconds % 3600) / 60 parts.append('%dh' % hours) seconds = seconds % 60 parts.append('%dm' % minutes) parts.append('%ds' % seconds) return avoid_wrapping(' '.join(parts))
def yearssince(d, now=None): # Convert datetime.date to datetime.datetime for comparison. if not isinstance(d, datetime.datetime): d = datetime.datetime(d.year, d.month, d.day) if now and not isinstance(now, datetime.datetime): now = datetime.datetime(now.year, now.month, now.day) if not now: now = datetime.datetime.now(utc if is_aware(d) else None) delta = now - d # ignore microseconds since = delta.days * 24 * 60 * 60 + delta.seconds if since <= 0: # d is in the future compared to now, stop processing. return avoid_wrapping(ugettext('0 minutes')) for i, (seconds, name) in enumerate(TIMESINCE_CHUNKS): count = since // seconds if count != 0: break result = avoid_wrapping(name % count) return result
def sizeformat(value, arg="B"): """ Formats the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102 byte_len, etc). """ try: byte_len = float(value) except (TypeError, ValueError, UnicodeDecodeError): value = ungettext("%(size)d byte", "%(size)d byte_len", 0) % { 'size': 0 } return avoid_wrapping(value) def filesize_number_format(val): return formats.number_format(round(val, 1), 1) # 在原函数的基础上,添加了单位参数,使不同量级数据都可以被格式化 switch = {'KB': KB, 'MB': MB, 'GB': GB, 'TB': TB, 'PB': PB} if arg in switch: byte_len *= switch[arg] if byte_len < KB: value = ungettext("%(size)d byte", "%(size)d byte_len", byte_len) % { 'size': byte_len } elif byte_len < MB: value = ugettext("%s KB") % filesize_number_format(byte_len / KB) elif byte_len < GB: value = ugettext("%s MB") % filesize_number_format(byte_len / MB) elif byte_len < TB: value = ugettext("%s GB") % filesize_number_format(byte_len / GB) elif byte_len < PB: value = ugettext("%s TB") % filesize_number_format(byte_len / TB) else: value = ugettext("%s PB") % filesize_number_format(byte_len / PB) return avoid_wrapping(value)
def leftbirt(d, now=None): if not now: now = datetime.date.now() if not isinstance(d, datetime.datetime): d = datetime.datetime(now.year, d.month, d.day) delta = d - now since = abs(delta.days * 24 * 60 * 60 + delta.seconds) // 3600 if since <= 72: for i, (seconds, name) in enumerate(TIMESINCE_CHUNKS): count = (since) result = avoid_wrapping(name % count) else: result = False return result
def relativetime(d): """ Takes a datetime object and returns a relative time string If time < 60 minutes: - vor 43 Minuten If time < 24 hours: - vor 12 Stunden If time == current year: - 5. Feb. If time != current year: - 2. Februar 1988 Adapted from: https://github.com/django/django/blob/8fa9a6d29efe2622872b4788190ea7c1bcb92019/django/utils/timesince.py (django/utils/timesince.py) Django date formats: https://docs.djangoproject.com/en/3.0/ref/templates/builtins/#date """ def add_ago(time_str, lang_code): return f'vor {time_str}' if lang_code == 'de' else f'{time_str} ago' # Convert datetime.date to datetime.datetime for comparison. if not isinstance(d, datetime.datetime): d = datetime.datetime(d.year, d.month, d.day) now = datetime.datetime.now(utc if is_aware(d) else None) delta = now - d # Deal with leapyears by subtracing the number of leapdays leapdays = calendar.leapdays(d.year, now.year) if leapdays != 0: if calendar.isleap(d.year): leapdays -= 1 elif calendar.isleap(now.year): leapdays += 1 delta -= datetime.timedelta(leapdays) # ignore microseconds since = delta.days * 24 * 60 * 60 + delta.seconds if since <= 0: # d is in the future compared to now, stop processing. return avoid_wrapping(TIME_STRINGS['minute'] % 0) lang_code = get_language() result = '' if since <= TIME_VALUES['minute']: time_str = TIME_STRINGS['second'] % since result = add_ago(time_str, lang_code) elif since <= TIME_VALUES['hour']: minutes = since // TIME_VALUES['minute'] time_str = TIME_STRINGS['minute'] % minutes result = add_ago(time_str, lang_code) elif since <= TIME_VALUES['day']: hours = since // TIME_VALUES['hour'] time_str = TIME_STRINGS['hour'] % hours result = add_ago(time_str, lang_code) elif d.year == now.year: if lang_code == 'de': result = date_format(d, 'j. N') # 18. Feb. else: result = date_format(d, 'M j.') # Feb 18. else: if lang_code == 'de': result = date_format(d, 'j. N Y') # 18. Feb. 2018 else: result = date_format(d, 'M j. Y') # Feb 18. 2018 return avoid_wrapping(result)
def kbdetailformat(bytes): return avoid_wrapping( _format_size(bytes * 1024, lambda x, y: ['%d %sB', '%.2f %sB'][bool(x)] % (y, x)))
def timesince(d, now=None, reversed=False, time_strings=None, depth=2): """ Take two datetime objects and return the time between d and now as a nicely formatted string, e.g. "10 minutes". If d occurs after now, return "0 minutes". Units used are years, months, weeks, days, hours, and minutes. Seconds and microseconds are ignored. Up to `depth` adjacent units will be displayed. For example, "2 weeks, 3 days" and "1 year, 3 months" are possible outputs, but "2 weeks, 3 hours" and "1 year, 5 days" are not. `time_strings` is an optional dict of strings to replace the default TIME_STRINGS dict. `depth` is an optional integer to control the number of adjacent time units returned. Adapted from https://web.archive.org/web/20060617175230/http://blog.natbat.co.uk/archive/2003/Jun/14/time_since """ if time_strings is None: time_strings = TIME_STRINGS if depth <= 0: raise ValueError("depth must be greater than 0.") # Convert datetime.date to datetime.datetime for comparison. if not isinstance(d, datetime.datetime): d = datetime.datetime(d.year, d.month, d.day) if now and not isinstance(now, datetime.datetime): now = datetime.datetime(now.year, now.month, now.day) now = now or datetime.datetime.now( datetime.timezone.utc if is_aware(d) else None) if reversed: d, now = now, d delta = now - d # Deal with leapyears by subtracing the number of leapdays leapdays = calendar.leapdays(d.year, now.year) if leapdays != 0: if calendar.isleap(d.year): leapdays -= 1 elif calendar.isleap(now.year): leapdays += 1 delta -= datetime.timedelta(leapdays) # ignore microseconds since = delta.days * 24 * 60 * 60 + delta.seconds if since <= 0: # d is in the future compared to now, stop processing. return avoid_wrapping(time_strings["minute"] % {"num": 0}) for i, (seconds, name) in enumerate(TIMESINCE_CHUNKS): count = since // seconds if count != 0: break else: return avoid_wrapping(time_strings["minute"] % {"num": 0}) result = [] current_depth = 0 while i < len(TIMESINCE_CHUNKS) and current_depth < depth: seconds, name = TIMESINCE_CHUNKS[i] count = since // seconds if count == 0: break result.append(avoid_wrapping(time_strings[name] % {"num": count})) since -= seconds * count current_depth += 1 i += 1 return gettext(", ").join(result)
def __html__(self): return mark_safe(avoid_wrapping(conditional_escape(self.__unicode__())))
def __html__(self): return mark_safe(avoid_wrapping(conditional_escape(str(self))))
def kbdetailformat(bytes): return avoid_wrapping(_format_size(bytes * 1024, lambda x, y: ['%d %sB', '%.2f %sB'][bool(x)] % (y, x)))
def __html__(self): return mark_safe(avoid_wrapping(conditional_escape( self.__unicode__())))
from __future__ import unicode_literals
def timesince(d, now=None, reversed=False, context=''): """ Take two datetime objects and return the time between d and now as a nicely formatted string, e.g. "10 minutes". If d occurs after now, return "0 minutes". Units used are years, months, weeks, days, hours, and minutes. Seconds and microseconds are ignored. Up to two adjacent units will be displayed. For example, "2 weeks, 3 days" and "1 year, 3 months" are possible outputs, but "2 weeks, 3 hours" and "1 year, 5 days" are not. Adapted from http://web.archive.org/web/20060617175230/http://blog.natbat.co.uk/archive/2003/Jun/14/time_since """ # Needed to fix #21408. if context: TIMESINCE_CHUNKS = ((60 * 60 * 24 * 365, npgettext_lazy(context, '%d year', '%d years')), (60 * 60 * 24 * 30, npgettext_lazy(context, '%d month', '%d months')), (60 * 60 * 24 * 7, npgettext_lazy(context, '%d week', '%d weeks')), (60 * 60 * 24, npgettext_lazy(context, '%d day', '%d days')), (60 * 60, npgettext_lazy(context, '%d hour', '%d hours')), (60, npgettext_lazy(context, '%d minute', '%d minutes'))) else: TIMESINCE_CHUNKS = ((60 * 60 * 24 * 365, ngettext_lazy('%d year', '%d years')), (60 * 60 * 24 * 30, ngettext_lazy('%d month', '%d months')), (60 * 60 * 24 * 7, ngettext_lazy('%d week', '%d weeks')), (60 * 60 * 24, ngettext_lazy('%d day', '%d days')), (60 * 60, ngettext_lazy('%d hour', '%d hours')), (60, ngettext_lazy('%d minute', '%d minutes'))) # Convert datetime.date to datetime.datetime for comparison. if not isinstance(d, datetime.datetime): d = datetime.datetime(d.year, d.month, d.day) if now and not isinstance(now, datetime.datetime): now = datetime.datetime(now.year, now.month, now.day) now = now or datetime.datetime.now(utc if is_aware(d) else None) if reversed: d, now = now, d delta = now - d # Deal with leapyears by subtracing the number of leapdays leapdays = calendar.leapdays(d.year, now.year) if leapdays != 0: if calendar.isleap(d.year): leapdays -= 1 elif calendar.isleap(now.year): leapdays += 1 delta -= datetime.timedelta(leapdays) # ignore microseconds since = delta.days * 24 * 60 * 60 + delta.seconds if since <= 0: # d is in the future compared to now, stop processing. return avoid_wrapping(gettext('0 minutes')) for i, (seconds, name) in enumerate(TIMESINCE_CHUNKS): count = since // seconds if count != 0: break result = avoid_wrapping(name % count) if i + 1 < len(TIMESINCE_CHUNKS): # Now get the second item seconds2, name2 = TIMESINCE_CHUNKS[i + 1] count2 = (since - (seconds * count)) // seconds2 if count2 != 0: result += gettext(', ') + avoid_wrapping(name2 % count2) return result
def inboxentime(value): """A filter much like Django's timesince and naturaltime, except it only gives the most significant unit. Much of this function was taken from Django 1.11.12 Copyright (c) Django Software Foundation and individual contributors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Django nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ if not isinstance(value, datetime): value = datetime(value.year, value.month, value.day) now = timezone.now() delta = now - value # Deal with leapyears by substracting leapdays leapdays = calendar.leapdays(value.year, now.year) if leapdays != 0: if calendar.isleap(value.year): leapdays -= 1 elif calendar.isleap(now.year): leapdays += 1 delta -= timedelta(leapdays) since = delta.days * 24 * 60 * 60 + delta.seconds if since <= 60: # if it's less than a minute ago, it was just now return avoid_wrapping(_("just now")) for i, (seconds, name) in enumerate(TIMESINCE_CHUNKS): count = since // seconds if count != 0: break name = name % count return avoid_wrapping(name)
"""Default variable filters."""