ago/ago.py
RussellBallestrini e95b5d8c10 python3.x merge caused issues with python2.x compat
instead of importing division from future we simply use int() to cast
floats to integers.

nosetests: on python2.7 passes
python2 test_ago.py: passes
python3 test_ago.py: passes

TODO: Does nosetests work with python3.x?

branch 'default'
changed ago.py
changed test_ago.py
2014-02-25 11:55:43 -05:00

38 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' : int(delta.days / 365),
'day' : int(delta.days % 365),
'hour' : int(delta.seconds / 3600),
'minute' : int(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 = []
count = 0
units = ( 'year', 'day', 'hour', 'minute', 'second', 'microsecond' )
for unit in units:
if count >= precision: break # met 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 ) )
count += 1
human_delta = ', '.join( hlist )
return the_tense.format(human_delta)