Added getDuration function ZTK-1.1
authorThierry Florac <tflorac@ulthar.net>
Fri, 23 Mar 2012 15:52:55 +0100
branchZTK-1.1
changeset 125 dec1ba47922a
parent 124 953f5b5bddb6
child 126 57d4ca60eb61
Added getDuration function
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