Skip to content

Instantly share code, notes, and snippets.

@alejandrobernardis
Created February 14, 2012 20:27
Show Gist options
  • Save alejandrobernardis/1830077 to your computer and use it in GitHub Desktop.
Save alejandrobernardis/1830077 to your computer and use it in GitHub Desktop.
Basic timesince
#: -- timesince ----------------------------------------------------------------
def get_plural(value, singular, plural, message=""):
try:
return plural if int(value) > 1 else singular
except:
return message
def get_str_plural(value, singular, plural, message="", tmpl=u"%s %s"):
return tmpl % (value, get_plural(value, singular, plural))
def timesince(delta, default=None):
if default is None:
default = u"justo ahora"
now = datetime.datetime.utcnow()
diff = now - delta
years = diff.days/365
months = diff.days/30
weeks = diff.days/7
days = diff.days
hours = diff.seconds/3600
minutes = diff.seconds/60
seconds = diff.seconds
periods = (
(years, get_str_plural(years, u"año", u"años")),
(months, get_str_plural(months, u"mes", u"meses")),
(weeks, get_str_plural(weeks, u"semana", u"semanas")),
(days, get_str_plural(days, u"día", u"días")),
(hours, get_str_plural(hours, u"hora", u"horas")),
(minutes, get_str_plural(minutes, u"minuto", u"minutos")),
(seconds, get_str_plural(seconds, u"segundo", u"segundos")),)
for period, trans in periods:
if period:
return "hace %(period)s" % {"period": trans}
return default
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment