2011-08-02 20 views
4

私はPythonでstrftimeで日付を書式設定できますが、現在は の日付を現在の時刻に相対的な形式で表示します。PythonでのGmail形式の日付書式設定

つまり、今日の日付が近いと表示されます。

それは一週間以内であれば、昨日のようにショーなど

それが月内であれば、単に最後の週または月として表示されます。

実際の値よりも古い場合は、

私は多くのifでそれを行うことができますが、これを行う簡単な方法はありますか?または図書館?日時値の場合

答えて

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] 
3

django.contrib.humanize.naturaltime

、それはして何秒、 分または数時間前表す文字列を返します - 背面に落下します の値が1日以上経過している場合は、より長い日付形式。日時の値が の場合、戻り値は自動的に適切なフレーズを使用します。

例(「今」2007年2月17日午後04時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を得ることができます。