Created
January 1, 2017 22:31
-
-
Save Fedjmike/035ae5cb4690e55b07438d744d0e018f to your computer and use it in GitHub Desktop.
Concise and precise relative datetime
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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