Skip to content

Instantly share code, notes, and snippets.

@ssokolow
Created August 5, 2010 05:29
Show Gist options
  • Select an option

  • Save ssokolow/509294 to your computer and use it in GitHub Desktop.

Select an option

Save ssokolow/509294 to your computer and use it in GitHub Desktop.
Relative interval pretty-printer for timestamps
def pretty_date(time=None, utc=False):
"""
Get a datetime object, time tuple, or int/float Epoch timestamp
and return a pretty string like 'an hour ago', 'Yesterday',
'3 months ago', 'just now', etc.
If utc=True, naive date comparisons will assume UTC rather than
the local timezone.
Modified to handle timezone-aware datetime instances, floats, and time tuples
Source: http://stackoverflow.com/questions/1551382/python-user-friendly-time-format
"""
from datetime import datetime, timedelta
if not time:
diff = timedelta(0)
if isinstance(time, (int, float)):
if utc:
diff = datetime.utcnow() - datetime.utcfromtimestamp(time)
else:
diff = datetime.now() - datetime.fromtimestamp(time)
elif isinstance(time, datetime):
if time.tzinfo is None:
if utc:
diff = datetime.utcnow() - time
else:
diff = datetime.now() - time
else:
diff = datetime.now(time.tzinfo) - time
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:
return str(day_diff/7) + " weeks ago"
if day_diff < 365:
return str(day_diff/30) + " months ago"
return str(day_diff/365) + " years ago"
@prabuinet
Copy link
Copy Markdown

Thanks for Posting

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment