ago/ago.py
RussellBallestrini 49ff995130 Removed need to keep track of counter, which reduces complexity
and chance of introducing errors, by slicing the the units tuple
by the percision.  Removed __main__ because nosetest --with-coverage
was flagging it.  It was un-nessasary.

Special thanks to Eric Rasmussen who inspired this commit.
2013-05-22 23:17:53 -04:00

35 lines
1.2 KiB
Python

from datetime import datetime
from datetime import timedelta
def delta2dict( delta ):
"""Accepts a delta, returns a dictionary of units"""
delta = abs( delta )
return {
'year' : delta.days / 365 ,
'day' : delta.days % 365 ,
'hour' : delta.seconds / 3600 ,
'minute' : (delta.seconds / 60) % 60 ,
'second' : delta.seconds % 60 ,
'microsecond' : delta.microseconds
}
def human(dt, precision=2, past_tense='{} ago', future_tense='in {}'):
"""Accept a datetime or timedelta, return a human readable delta string"""
delta = dt
if type(dt) is not type(timedelta()):
delta = datetime.now() - dt
the_tense = past_tense
if delta < timedelta(0):
the_tense = future_tense
d = delta2dict( delta )
hlist = []
units = ( 'year', 'day', 'hour', 'minute', 'second', 'microsecond' )
for unit in units[:precision]: # strip units to precision
if d[ unit ] == 0: continue # skip 0's
s = '' if d[ unit ] == 1 else 's' # handle plurals
hlist.append( '%s %s%s' % ( d[unit], unit, s ) )
human_delta = ', '.join( hlist )
return the_tense.format(human_delta)