Natural/Relative days in Python

前端 未结 6 1087
南旧
南旧 2020-11-30 03:44

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\",

6条回答
  •  有刺的猬
    2020-11-30 04:22

    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.

提交回复
热议问题