Python 中的自然/相对天数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/410221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Natural/Relative days in Python
提问by jamtoday
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.
我想要一种在 Python 中显示过时项目的自然时间的方法。类似于 Twitter 如何显示来自“刚才”、“几分钟前”、“两小时前”、“三天前”等的消息。
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.
Django 1.0 在 django.contrib 中有一个“humanize”方法。我没有使用 Django 框架,即使我使用,它也比我想要的更有限。
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.
请让我(以及几代未来的搜索者)知道是否已经有一个好的工作解决方案。由于这是一项足够常见的任务,我想一定有什么。
采纳答案by runeh
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:
虽然此刻对您没有用处,但对于未来的搜索者来说可能有用: babel 模块处理各种语言环境,具有或多或少做您想做的功能。目前它只在他们的后备箱中,而不是在最新的公开版本(0.9.4 版)中。一旦功能发布到版本中,您可以执行以下操作:
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.
这直接取自关于时间增量格式的 babel 文档。这至少会让你部分完成。它不会将模糊性降低到“片刻前”等级别,但它会正确地将“n 分钟”等进行复数化。
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.
值得一提的是,babel 模块还包含根据区域设置格式化日期和时间的函数,这在时间增量很大时可能很有用。
回答by Josh Segall
Twitter dates in specific are interesting because they are relative only for the first day. After 24 hours they just show the month and day. After a year they start showing the last two digits of the year. Here's a sample function that does something more akin to Twitter relative dates, though it always shows the year too after 24 hours. It's US locale only, but you can always alter it as needed.
Twitter 日期特别有趣,因为它们仅在第一天是相对的。24 小时后,他们只显示月份和日期。一年后,他们开始显示年份的最后两位数字。这是一个示例函数,它执行更类似于 Twitter 相对日期的操作,尽管它总是在 24 小时后显示年份。它仅适用于美国语言环境,但您可以随时根据需要更改它。
# tested in Python 2.7
import datetime
def prettydate(d):
diff = datetime.datetime.utcnow() - d
s = diff.seconds
if diff.days > 7 or diff.days < 0:
return d.strftime('%d %b %y')
elif diff.days == 1:
return '1 day ago'
elif diff.days > 1:
return '{} days ago'.format(diff.days)
elif s <= 1:
return 'just now'
elif s < 60:
return '{} seconds ago'.format(s)
elif s < 120:
return '1 minute ago'
elif s < 3600:
return '{} minutes ago'.format(s/60)
elif s < 7200:
return '1 hour ago'
else:
return '{} hours ago'.format(s/3600)
回答by sevenforce
There is the humanize package:
有人性化的包:
>>> import humanize
>>> import datetime
>>> humanize.naturalday(datetime.datetime.now())
'today'
>>> humanize.naturalday(datetime.datetime.now() - datetime.timedelta(days=1))
'yesterday'
>>> humanize.naturalday(datetime.date(2007, 6, 5))
'Jun 05'
>>> humanize.naturaldate(datetime.date(2007, 6, 5))
'Jun 05 2007'
>>> humanize.naturaltime(datetime.datetime.now() - datetime.timedelta(seconds=1))
'a second ago'
>>> humanize.naturaltime(datetime.datetime.now() - datetime.timedelta(seconds=3600))
'an hour ago'
Examples for your use case:
您的用例的示例:
>>> humanize.naturaltime(datetime.datetime.now() - datetime.timedelta(seconds=36000))
'10 hours ago'
>>> humanize.naturaltime(datetime.datetime.now() - datetime.timedelta(seconds=360000))
'4 days ago'
>>> humanize.naturaltime(datetime.datetime.now() - datetime.timedelta(seconds=3600000))
'a month ago'
Further (see link above) it also supports humanization of:
此外(见上面的链接)它还支持人性化:
- integers
- file sizes
- floats (to fractional numbers)
- 整数
- 文件大小
- 浮点数(到小数)
回答by lpfavreau
Or you could easily adapt timesince.pyfrom 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).
或者,您可以轻松地从 Django 中调整timesince.py,它本身只有 2 个其他依赖项:一个用于翻译(您可能不需要),另一个用于时区(可以轻松调整)。
By the way, Django has a BSD licensewhich is pretty flexible, you'll be able to use it in whatever project you are currently using.
顺便说一下,Django 有一个非常灵活的 BSD 许可证,你可以在你当前使用的任何项目中使用它。
回答by lpfavreau
Are you looking for something like this(Printing Relative Dates in Python)?
您是否正在寻找这样的东西(在 Python 中打印相对日期)?
回答by Radu Gabriel
Found out that obe can use maya
like this
发现,OBE可以使用maya
这样的
pip install maya
>>> maya.when("3 week ago").datetime().strftime("%Y-%m-%d")
'2020-04-27'