views:

942

answers:

3

I'd like a way to show natural times for dated items in Python. Similar to how Twitter will show a message from "a moment ago", "a few minutes ago", "two hours ago", "three days ago", etc.

Django 1.0 has a "humanize" method in django.contrib. I'm not using the Django framework, and even if I were, it's more limited than what I'd like.

Please let me (and generations of future searchers) know if there is a good working solution already. Since this is a common enough task, I imagine there must be something.

+3  A: 

Are you looking for something like this (Printing Relative Dates in Python)?

lpfavreau
+5  A: 

Or you could easily adapt timesince.py from Django which only has 2 other dependencies to itself: one for translation (which you might not need) and one for timezones (which can be easily adapted).

By the way, Django has a BSD license which is pretty flexible, you'll be able to use it in whatever project you are currently using.

lpfavreau
+6  A: 

While not useful to you at this very moment, it may be so for future searchers: The babel module, which deals with all sorts of locale stuff, has a function for doing more or less what you want. Currently it's only in their trunk though, not in the latest public release (version 0.9.4). Once the functionality lands in a release, you could do something like:

from datetime import timedelta
from babel.dates import format_timedelta
delta = timedelta(days=6)
format_timedelta(delta, locale='en_US')
u'1 week'

This is taken straight from the babel documentation on time delta formatting. This will at least get you parts of the way. It wont do fuzziness down to the level of "moments ago" and such, but it will do "n minutes" etc. correctly pluralized.

For what it's worth, the babel module also contains functions for formatting dates and times according to locale, Which might be useful when the time delta is large.

runeh