Skip to content

Instantly share code, notes, and snippets.

@bbrodriges
Created December 24, 2012 12:08
Show Gist options
  • Save bbrodriges/4369042 to your computer and use it in GitHub Desktop.
Save bbrodriges/4369042 to your computer and use it in GitHub Desktop.
Convert UNIX timestamp into human readable time delta. E.g.: 1356354501 -> "10 minutes ago"
def unix_to_delta(self, timestamp):
"""
@type timestamp int
@return str
Converts UNIX timestamp into human readable time delta.
E.g.: "10 minutes ago"
"""
# defining UNIX time constants
minute = 60
hour = minute * 60
day = hour * 24
month = day * 30
year = month * 12
# getting time delta
delta = int(time()) - timestamp
# desiding which time to use
result, plural = 'right now', None
if delta < minute:
delta, plural = int(delta), 'second%s'
elif minute <= delta < hour:
delta, plural = int(math.floor(delta / minute)), 'minute%s'
elif hour <= delta < day:
delta, plural = int(math.floor(delta / hour)), 'hour%s'
elif day <= delta < month:
delta, plural = int(math.floor(delta / day)), 'day%s'
elif month <= delta < year:
delta, plural = int(math.floor(delta / month)), 'month%s'
elif year <= delta:
delta, plural = int(math.floor(delta / year)), 'year%s'
# polishing result
if plural:
plural %= 's'[delta == 1:]
result = '%i %s ago' % (delta, plural)
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment