How to format a timedelta like "1 hour ago" in python so that it is translatable
datetime, internationalization, python
Solution
According to documentation I found here, you should add the `add_direction=True` parameter to your `format_timedelta` call.
Problem
I want to format a python timedelta object as "x minutes/hours/weeks/month/years ago". I know there are some similar questions, like: - How to display "x days ago" type time using Humanize in Django template? - From: "1 hour ago", To: timedelta + accuracy - User-friendly time format in Python? However, I did not find an answer for my case, because - I do not use django - I need to format a `timedelta` to a string, not the other way around - The solution should work in as many languages as possible, not just English Here 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.