Is there a python module that helps you to display dates and times
nice e.g.
just now (for within the last 5 minutes)
2 hours ago
2 days ago
15th February 2009
...
I guess somebody must have done that already, right?
def prettydate(d):
try:
dt = request.now - d
except:
return ''
if dt.days>=365*2:
return '%s years ago' % int(dt.days/365)
elif dt.days>=365:
return '1 years ago'
elif dt.days>=60:
return '%s months ago' % int(dt.days/30)
elif dt.days>21:
return '1 months ago'
elif dt.days>=14:
return '%s weeks ago' % int(dt.days/7)
elif dt.days>=7:
return '1 week ago'
elif dt.days>=2:
return '%s days ago' % int(dt.days)
elif dt.days==1:
return '1 day ago'
else:
return 'today'
def prettydate(d):
try:
dt = datetime.now() - d
except:
return ''
if dt.days >= 2*365:
return '%d years ago' % int(dt.days / 365)
elif dt.days >= 365:
return '1 year ago'
elif dt.days >= 60:
return '%d months ago' % int(dt.days / 30)
elif dt.days > 21:
return '1 month ago'
elif dt.days >= 14:
return '%d weeks ago' % int(dt.days / 7)
elif dt.days >= 7:
return '1 week ago'
elif dt.days > 1:
return '%d days ago' % dt.days
elif dt.days == 1:
return '1 day ago'
elif dt.seconds >= 2*60*60:
return '%d hours ago' % int(dt.seconds / 3600)
elif dt.seconds >= 60*60:
return '1 hour ago'
elif dt.seconds >= 2*60:
return '%d minutes ago' % int(dt.seconds / 60)
elif dt.seconds >= 60:
return '1 minute ago'
elif dt.seconds > 1:
return '%d seconds ago' % dt.seconds
elif dt.seconds == 1:
return '1 second ago'
else:
return 'now'
So, we need some extra flavor to compensate the time a guy spent to
find our prettydate(). How about making it i18n-friendly? Something
like this.
class PrettyDate(object):
def __init__(self,T):
self.T=T #
def __call__(self, d):
dt = datetime.now() - d
if dt.days >= 2*365:
return self.T('%d years ago') % int(dt.days / 365)
elif ...:
......
Then, in the model we can initialize an instance by:
prettydate = PrettyDate(T)
In controller we can do:
prettydate(d)
Of course developers need to localize their own language strings in
their own environment.
Just my $0.02
>
prettydate(request.now,T)