Skip to content

Instantly share code, notes, and snippets.

@xv
Created April 10, 2019 14:30
Show Gist options
  • Save xv/bfff0705662a16ad811665ddd08298ea to your computer and use it in GitHub Desktop.
Save xv/bfff0705662a16ad811665ddd08298ea to your computer and use it in GitHub Desktop.
Returns the relative time (also known as 'time ago') based on the given datetime object input.
from datetime import datetime
from math import floor
def get_relative_time(dateTime):
current_time = datetime.utcnow()
time_diff = current_time - dateTime
intervals = (
(time_diff.days / 36500, "century", "centuries"),
(time_diff.days / 3650, "decade", "decades"),
(time_diff.days / 365, "year", "years"),
(time_diff.days / 30, "month", "months"),
(time_diff.days / 7, "week", "weeks"),
(time_diff.days, "day", "days"),
(time_diff.seconds / 3600, "hour", "hours"),
(time_diff.seconds / 60, "minute", "minutes"),
(time_diff.seconds, "second", "seconds"),
)
for i, s, p in intervals:
time_ago = floor(i)
if time_ago:
# Singular if the returned floor value is 1, plural otherwise
return f"{time_ago} {s if time_ago == 1 else p} ago"
return "Just now"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment