Skip to content

Instantly share code, notes, and snippets.

@evandempsey
Created October 15, 2018 15:13
Show Gist options
  • Save evandempsey/c9d2edd272454d9ed033de95d828ecc2 to your computer and use it in GitHub Desktop.
Save evandempsey/c9d2edd272454d9ed033de95d828ecc2 to your computer and use it in GitHub Desktop.
from datetime import datetime
def readable_time_elapsed(since):
"""
Generates a string with an informal English text representation of the
time that has elapsed between now and a given time.
Modified from some StackOverflow answer that I have lost.
:param since:
:return:
"""
delta = datetime.now() - since
seconds_delta = delta.seconds
days_delta = delta.days
if days_delta < 0:
return ''
if days_delta == 0:
if seconds_delta < 10:
return "Just now"
if seconds_delta < 60:
return "{0} seconds ago".format(seconds_delta)
if seconds_delta < 120:
return "A minute ago"
if seconds_delta < 3600:
return "{0} minutes ago".format(seconds_delta // 60)
if seconds_delta < 7200:
return "An hour ago"
if seconds_delta < 86400:
return "{0} hours ago".format(seconds_delta // 3600)
if days_delta == 1:
return "Yesterday"
if days_delta < 7:
return "{0} days ago".format(days_delta)
if days_delta < 31:
num_weeks = days_delta // 7
if num_weeks == 1:
return "A week ago"
return "{0} weeks ago".format(num_weeks)
if days_delta < 365:
num_months = days_delta // 30
if num_months == 1:
return "A month ago"
return "{0} months ago".format(num_months)
return "{0} years ago".format(days_delta // 365)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment