From 89d73aa9dd5dc0fe8db844feedb8f059ec2b8d30 Mon Sep 17 00:00:00 2001 From: RussellBallestrini Date: Tue, 8 Jan 2013 20:43:48 -0500 Subject: [PATCH] Integrated David Beitey's code (https://bitbucket.org/davidjb) https://bitbucket.org/russellballestrini/ago/pull-request/1/add-support-for-future-dates-minor-readme/ --- ago.py | 23 ++++++++++++++--------- test_ago.py | 8 ++++---- 2 files changed, 18 insertions(+), 13 deletions(-) diff --git a/ago.py b/ago.py index 14f93b9..6dc218c 100644 --- a/ago.py +++ b/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 diff --git a/test_ago.py b/test_ago.py index 4c993ae..865b5cf 100644 --- a/test_ago.py +++ b/test_ago.py @@ -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 ''