Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gmail style date formatting in python

I can format date with strftime in python, but now I want to show date in format relative to current time.

i.e. if date is near today, show in time.

if it is within week, show as yesterday etc.

if it is within month just show as last week or month.

if it is older than that show as actual value.

I can do it with lots of ifs but is there any simpler way to do this? or library?

like image 443
iamgopal Avatar asked Jan 19 '23 02:01

iamgopal


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]
like image 59
lprsd Avatar answered Jan 28 '23 03:01

lprsd


django.contrib.humanize.naturaltime

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

Examples (when ‘now’ is 17 Feb 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 the sources here.

like image 36
Paolo Moretti Avatar answered Jan 28 '23 03:01

Paolo Moretti