# HG changeset patch # User Thierry Florac # Date 1332514375 -3600 # Node ID dec1ba47922a345245745dba0fbb97304c362009 # Parent 953f5b5bddb61cadd0189f2b76c54757aa95306e Added getDuration function diff -r 953f5b5bddb6 -r dec1ba47922a ztfy/utils/date.py --- a/ztfy/utils/date.py Fri Mar 23 15:52:37 2012 +0100 +++ b/ztfy/utils/date.py Fri Mar 23 15:52:55 2012 +0100 @@ -103,3 +103,31 @@ return translate(_("%d minutes ago")) % int(round(delta.seconds * 1.0 / 60)) else: return translate(_("less than 5 minutes ago")) + + +def getDuration(v1, v2=None): + """Get delta between two dates""" + if v2 is None: + v2 = datetime.utcnow() + assert isinstance(v1, datetime) and isinstance(v2, datetime) + v1, v2 = min(v1, v2), max(v1, v2) + delta = v2 - v1 + if delta.days > 60: + return translate(_("%d months")) % int(round(delta.days * 1.0 / 30)) + elif delta.days > 10: + return translate(_("%d weeks")) % int(round(delta.days * 1.0 / 7)) + elif delta.days >= 2: + return translate(_("%d days")) % delta.days + else: + hours = int(round(delta.seconds * 1.0 / 3600)) + if delta.days == 1: + return translate(_("%d day and %d hours")) % (delta.days, hours) + else: + if hours > 2: + return translate(_("%d hours")) % hours + else: + minutes = int(round(delta.seconds * 1.0 / 60)) + if minutes > 2: + return translate(_("%d minutes")) % minutes + else: + return translate(_("%d seconds")) % delta.seconds