Python gmail style date formatting

I can format the date using strftime in python, but now I want to display the date in a format relative to the current time.

i.e. if the date is close to today, show on time.

if it is within a week, it is displayed as yesterday, etc.

if it is displayed during the month only last week or in the month.

if it is older than shown as the actual value.

I can do this with more ifs, but is there an easier way to do this? or libraries?

+4
source share
2 answers

There is a library

From 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] 
+6
source

django.contrib.humanize.naturaltime

For values, datetime returns a string representing how many seconds, minutes or hours ago, it was a return to a longer date format if the value is more than one day. In case the datetime value is specified in the future, the return value will automatically use the corresponding phrase.

Examples (when "now February 17, 2007 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. 

You can get sources here .

+3
source

All Articles