Integrated David Beitey's code (https://bitbucket.org/davidjb)
https://bitbucket.org/russellballestrini/ago/pull-request/1/add-support-for-future-dates-minor-readme/
This commit is contained in:
parent
87afe070a3
commit
89d73aa9dd
2 changed files with 18 additions and 13 deletions
23
ago.py
23
ago.py
|
|
@ -1,3 +1,6 @@
|
|||
from datetime import datetime
|
||||
from datetime import timedelta
|
||||
|
||||
def delta2dict( delta ):
|
||||
"""return dictionary of delta"""
|
||||
return {
|
||||
|
|
@ -9,27 +12,29 @@ def delta2dict( delta ):
|
|||
'microsecond' : delta.microseconds
|
||||
}
|
||||
|
||||
def delta2human( delta, precision = 2 ):
|
||||
def delta2human(delta, precision=2, past_format='{0} ago', future_format='in {0}'):
|
||||
"""return human readable delta string"""
|
||||
units = ( 'year', 'day', 'hour', 'minute', 'second', 'microsecond' )
|
||||
the_format = past_format
|
||||
if delta < timedelta(0): # if true delta is in future
|
||||
the_format = future_format
|
||||
delta = abs( delta )
|
||||
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
|
||||
return ', '.join( hlist )
|
||||
human_delta = ', '.join( hlist )
|
||||
return the_format.format(human_delta)
|
||||
|
||||
def human( d1, precision = 2 ):
|
||||
def human(d, precision=2, format_past='{0} ago', format_future='in {0}'):
|
||||
"""Pass datetime we will return human delta string"""
|
||||
from datetime import datetime
|
||||
d2 = datetime.now()
|
||||
delta = d2 - d1
|
||||
if d2 < d1: delta = d1 - d2
|
||||
return delta2human( delta, precision )
|
||||
delta = datetime.now() - d
|
||||
return delta2human( delta, precision, format_past, format_future )
|
||||
|
||||
if __name__ == "__main__":
|
||||
from test_ago import test_output
|
||||
|
|
|
|||
|
|
@ -34,12 +34,12 @@ def test_output():
|
|||
|
||||
print '\nTesting past:\n'
|
||||
print delta2dict( PAST_DELTA )
|
||||
print 'Commented ' + delta2human( PAST_DELTA, 3 ) + ' ago'
|
||||
print 'Commented ' + human( PAST ) + ' ago'
|
||||
print 'Commented ' + delta2human( PAST_DELTA, 3 )
|
||||
print 'Commented ' + human( PAST )
|
||||
|
||||
print '\nTesting future:\n'
|
||||
print delta2dict( FUTURE_DELTA )
|
||||
print 'Shutdown in ' + delta2human( FUTURE_DELTA, 3 )
|
||||
print 'Shutdown in ' + human( FUTURE )
|
||||
print 'Shutdown ' + delta2human( FUTURE_DELTA, 3 )
|
||||
print 'Shutdown ' + human( FUTURE )
|
||||
print ''
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue