]> de.git.xonotic.org Git - xonotic/xonstat.git/blobdiff - xonstat/util.py
Add fuzzy dates.
[xonotic/xonstat.git] / xonstat / util.py
old mode 100644 (file)
new mode 100755 (executable)
index 1b54426..e9d179a
@@ -1,10 +1,12 @@
 import re
+from datetime import datetime
 
 def strip_colors(str=None):
     str = re.sub(r'\^x\w\w\w', '', str)
     str = re.sub(r'\^\d', '', str)
     return str
 
+
 def html_colors(str=None):
     orig = str
     str = re.sub(r'\^x(\w)(\w)(\w)', 
@@ -25,5 +27,59 @@ def html_colors(str=None):
 
     return str
 
+
 def page_url(page):
     return current_route_url(request, page=page, _query=request.GET)
+
+
+def pretty_date(time=False):
+    """
+    Get a datetime object or a int() Epoch timestamp and return a
+    pretty string like 'an hour ago', 'Yesterday', '3 months ago',
+    'just now', etc
+    """
+    now = datetime.now()
+    if type(time) is int:
+        diff = now - datetime.fromtimestamp(time)
+    elif isinstance(time,datetime):
+        diff = now - time 
+    elif not time:
+        diff = now - now
+    second_diff = diff.seconds
+    day_diff = diff.days
+
+    if day_diff < 0:
+        return ''
+
+    if day_diff == 0:
+        if second_diff < 10:
+            return "just now"
+        if second_diff < 60:
+            return str(second_diff) + " seconds ago"
+        if second_diff < 120:
+            return  "a minute ago"
+        if second_diff < 3600:
+            return str( second_diff / 60 ) + " minutes ago"
+        if second_diff < 7200:
+            return "an hour ago"
+        if second_diff < 86400:
+            return str( second_diff / 3600 ) + " hours ago"
+    if day_diff == 1:
+        return "Yesterday"
+    if day_diff < 7:
+        return str(day_diff) + " days ago"
+    if day_diff < 31:
+        if day_diff/7 == 1:
+            return "a week ago"
+        else:
+            return str(day_diff/7) + " weeks ago"
+    if day_diff < 365:
+        if day_diff/30 == 1:
+            return "a month ago"
+        else:
+            return str(day_diff/30) + " months ago"
+    else:
+        if day_diff/365 == 1:
+            return "a year ago"
+        else:
+            return str(day_diff/365) + " years ago"