ppdate

From pp date, 5 Years ago, written in Python, viewed 1'732 times.
URL http://stikked.luisaranguren.com/view/8b263207 Embed
Download Paste or View Raw
  1. import datetime as datetime
  2.  
  3. def pretty_date(time=False):
  4.     """
  5.    Get a datetime object or a int() Epoch timestamp and return a
  6.    pretty string like 'an hour ago', 'Yesterday', '3 months ago',
  7.    'just now', etc
  8.    """
  9.     now = datetime.datetime.now()
  10.     if type(time) is int:
  11.         diff = now - datetime.datetime.fromtimestamp(time)
  12.     elif isinstance(time,datetime.datetime):
  13.         diff = now - time
  14.     elif not time:
  15.         diff = now - now
  16.     second_diff = diff.seconds
  17.     day_diff = diff.days
  18.  
  19.     if day_diff < 0:
  20.         return ''
  21.  
  22.     if day_diff == 0:
  23.         if second_diff < 10:
  24.             return "just now"
  25.         if second_diff < 60:
  26.             return str(second_diff) + " seconds ago"
  27.         if second_diff < 120:
  28.             return "a minute ago"
  29.         if second_diff < 3600:
  30.             return str(second_diff / 60) + " minutes ago"
  31.         if second_diff < 7200:
  32.             return "an hour ago"
  33.         if second_diff < 86400:
  34.             return str(second_diff / 3600) + " hours ago"
  35.     if day_diff == 1:
  36.         return "Yesterday"
  37.     if day_diff < 7:
  38.         return str(day_diff) + " days ago"
  39.     if day_diff < 31:
  40.         return str(day_diff / 7) + " weeks ago"
  41.     if day_diff < 365:
  42.         return str(day_diff / 30) + " months ago"
  43.     return str(day_diff / 365) + " years ago"

Reply to "ppdate"

Here you can reply to the paste above