I want to format a python timedelta object as "x minutes/hours/weeks/month/years ago".
I know there are some similar questions, like:
However, I did not find an answer for my case, because
timedelta
to a string, not the other way aroundHere is my current code (excerpt, sorry):
delta = babel.dates.format_timedelta(now - dt, format=format,
locale=locale)
if now > dt:
return _(u"%(timedelta)s ago") % {'timedelta': delta}
else:
return _(u"in %(timedelta)s") % {'timedelta': delta}
For the babel
function, see http://babel.pocoo.org/docs/dates/#time-delta-formatting
Now this works fine in English. In German, however, it fails:
The above code would translate "2 years ago"
to "vor 2 Jahre"
instead of "vor 2 Jahren"
.
I would also be happy with a solution that does not use the "... ago"
phrasing. As long as it is similar and translatable I can accept it.
According to documentation I found here, you should add the add_direction=True
parameter to your format_timedelta
call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With