Skip to content

Instantly share code, notes, and snippets.

@Fedjmike
Created January 1, 2017 22:31
Show Gist options
  • Save Fedjmike/035ae5cb4690e55b07438d744d0e018f to your computer and use it in GitHub Desktop.
Save Fedjmike/035ae5cb4690e55b07438d744d0e018f to your computer and use it in GitHub Desktop.
Concise and precise relative datetime
def relative_datetime(then):
delta = arrow.now() - then
years, days_of_year = delta.days // 365, delta.days % 365
months_of_year, days_of_month = days_of_year // 30, days_of_year % 30
hours_of_day, seconds_of_hour = delta.seconds // (60*60), delta.seconds % (60*60)
minutes_of_hour, seconds_of_minute = seconds_of_hour // 60, seconds_of_hour % 60
if years != 0:
return "%dy" % years if months_of_year == 0 \
else "%dy %dm" % (years, months_of_year)
elif months_of_year != 0:
return "%dm" % months_of_year if days_of_month == 0 \
else "%dm %dd" % (months_of_year, days_of_month)
elif days_of_month != 0:
return "%dd" % days_of_month if hours_of_day == 0 \
else "%dd %dh" % (days_of_month, hours_of_day)
elif hours_of_day != 0:
return "%dh" % hours_of_day if minutes_of_hour == 0 \
else "%dh %dm" % (hours_of_day, minutes_of_hour)
elif minutes_of_hour != 0:
return "%dm" % minutes_of_hour
else:
return "just now"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment