Skip to content

Instantly share code, notes, and snippets.

@maplambda
Created September 2, 2012 10:35
Show Gist options
  • Save maplambda/3596595 to your computer and use it in GitHub Desktop.
Save maplambda/3596595 to your computer and use it in GitHub Desktop.
friendly-age.py
import math
import time
def get_universal_time():
return time.time()
def plural(n, word):
return word if n == 1 else word + "s"
age_units = [("year", 365.25 * 24 * 60 * 60),
("week", 7 * 24 * 60 * 60),
("day", 24 * 60 * 60),
("hour", 60 * 60),
("minute", 60),
("second", 1)]
def friendly_age(time):
age = math.floor(get_universal_time() - time)
units = list(age_units)
while(units and age < units[0][1]):
units = units[1:]
name, value = units[0] if units else (None, None)
if not name:
return 'now'
v = math.floor(age / value)
return '%G %s' % (v, plural(v, name))
if __name__ == "__main__":
# future returns now
print friendly_age(get_universal_time() + 60 * 2)
# now
print friendly_age(get_universal_time())
# 1 second
print friendly_age(get_universal_time() - 1)
# 1 minute
print friendly_age(get_universal_time() - 60)
# 2 minutes
print friendly_age(get_universal_time() - 60 * 2)
# 1 week
print friendly_age(get_universal_time() - 604800)
# 2 weeks
print friendly_age(get_universal_time() - 604800 * 2)
# 1 year (1.5)
print friendly_age(get_universal_time() - 31557600.0 * 1.5)
# 2 year
print friendly_age(get_universal_time() - 31557600.0 * 2)
# 1 hour
print friendly_age(get_universal_time() - 3600)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment