python中的gmail样式日期格式

时间:2011-08-02 08:22:27

标签: python date format

我可以在python中使用strftime格式化日期,但现在我要显示 日期格式相对于当前时间。

即。如果日期接近今天,请及时显示。

如果是在一周内,则显示为昨天等。

如果是在月内,只显示为上周或月。

如果它比那个显示为实际值。

我可以用很多ifs来做,但有没有更简单的方法来做到这一点?还是图书馆?

2 个答案:

答案 0 :(得分:6)

is a library

来自the documentation

[python]
>>> from relativeDates import *
>>> import time
>>> x = time.time()-1000
>>> getRelativeTime(x)
'17 minutes ago'
>>> x-=12345
>>> getRelativeTime(x)
'3 hours ago'
>>> x+=543211
>>> getRelativeTime(x)
'in 6 days'
>>> getRelativeTime(x,accuracy=2)
'in 6 days 3 hours'
>>> x-=987661
>>> getRelativeTime(x,accuracy=2)
'5 days 7 hours ago'
>>> getRelativeTime(x,accuracy=2,alternative_past="long long ago")
'long long ago'
>>> getRelativeTimeStr("07/15/06 1823")
'in 4 days'
>>> getRelativeTimeStr("07/10/06 1823")
'7 hours ago'
>>> getRelativeTimeStr("07/10/06 1823",accuracy=2)
'7 hours 30 mins ago'
[/python]

答案 1 :(得分:3)

django.contrib.humanize.naturaltime

  

对于datetime值,返回表示秒数的字符串,   几分钟或几小时之前,它是 - 如果回到更长的日期格式   价值超过一天。如果日期时间值在   将来,返回值将自动使用适当的短语。

     

示例('now'是2007年2月17日16:30:00):

17 Feb 2007 16:30:00 becomes now.
17 Feb 2007 16:29:31 becomes 29 seconds ago.
17 Feb 2007 16:29:00 becomes a minute ago.
17 Feb 2007 16:25:35 becomes 4 minutes ago.
17 Feb 2007 15:30:29 becomes an hour ago.
17 Feb 2007 13:31:29 becomes 2 hours ago.
16 Feb 2007 13:31:29 becomes 1 day ago.
17 Feb 2007 16:30:30 becomes 29 seconds from now.
17 Feb 2007 16:31:00 becomes a minute from now.
17 Feb 2007 16:34:35 becomes 4 minutes from now.
17 Feb 2007 16:30:29 becomes an hour from now.
17 Feb 2007 18:31:29 becomes 2 hours from now.
18 Feb 2007 16:31:29 becomes 1 day from now.

您可以获取来源here