Python中的自然/相对天 [英] Natural/Relative days in Python
问题描述
Django 1.0在django.contrib中有一个人性化的方法。我没有使用Django框架,即使我是这样,它比我想要的更有限。
请让我(和未来的几代人)知道是否有一个很好的工作解决方案。既然这是一个很常见的任务,我想象必须有一些东西。
虽然在这个时候对你没有用处,可能对于未来的搜索者来说:
babel模块它处理各种各样的区域设置,具有或多或少做任何所需的功能。目前,它只在他们的主干,而不是在最新的公开版本(0.9.4版本)。一旦功能登陆发布,您可以执行以下操作:
from datetime import timedelta
pre>
from babel.dates import format_timedelta
delta = timedelta(days = 6)
format_timedelta(delta,locale ='en_US')
u'1 week'
这是直接从关于时间差异格式的babel文档。这将至少让你的方式。它不会将模糊性降到之前的水平,这样,但它会做n分钟等正确复数。
对于什么是值得的, babel模块还包含根据区域设置格式化日期和时间的功能,当时间增量较大时,可能会有用。
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.
解决方案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.
这篇关于Python中的自然/相对天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!