def delta2dict( delta ): """return dictionary of 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 delta2human( delta, precision = 2 ): """return human readable delta string""" units = ( 'year', 'day', 'hour', 'minute', 'second', 'microsecond' ) d = delta2dict( delta ) hlist = [] count = 0 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 ) def human( d1, precision = 2 ): """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 ) def test(): """Test and example usage""" from datetime import datetime from datetime import timedelta present = datetime.now() past = present - timedelta( 492, 58711, 45 ) # days, secs, ms future = present + timedelta( 2, 12447, 963 ) # days, secs, ms pdelta = present - past fdelta = future - present print '\nTesting past:\n' print delta2dict( pdelta ) print 'Commented ' + delta2human( pdelta, 3 ) + ' ago' print 'Commented ' + human( past ) + ' ago' print '\nTesting future:\n' print delta2dict( fdelta ) print 'Shutdown in ' + delta2human( fdelta, 3 ) print 'Shutdown in ' + human( future ) print '' if __name__ == "__main__": test()