Last active
December 28, 2015 09:19
-
-
Save eternicode/7478166 to your computer and use it in GitHub Desktop.
humanized interval formatter that works with both past and future times
This file contains 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
# Adapted from https://github.com/jtushman/human_dates | |
from datetime import datetime | |
from django.template.defaultfilters import pluralize | |
def prettyinterval(time=None): | |
""" | |
Take a datetime object and return a pretty string like 'in an hour', | |
'tomorrow', 'in 3 months', 'just now', etc | |
""" | |
now = datetime.utcnow() | |
past = True | |
diff = now - time | |
if diff.days < 0: | |
past = False | |
diff = time - now | |
format = '%s ago' if past else 'in %s' | |
second_diff = diff.seconds | |
day_diff = diff.days | |
txt = '' | |
if day_diff == 0: | |
if second_diff < 10 and past: | |
return 'just now' | |
elif second_diff < 60: | |
txt = '%s second%s' % (second_diff, pluralize(second_diff)) | |
elif second_diff < 120: | |
txt = 'a minute' | |
elif second_diff < 3600: | |
txt = '%s minute%s' % (second_diff/60, pluralize(second_diff/60)) | |
elif second_diff < 7200: | |
txt = 'an hour' | |
elif second_diff < 86400: | |
txt = '%s hour%s' % (second_diff/3600, pluralize(second_diff/3600)) | |
elif day_diff == 1: | |
return 'yesterday' if past else 'tomorrow' | |
elif day_diff < 7: | |
txt = '%s days' % day_diff | |
elif day_diff < 31: | |
txt = '%s week%s' % (day_diff/7, pluralize(day_diff/7)) | |
elif day_diff < 365: | |
txt = '%s month%s' % (day_diff/30, pluralize(day_diff/30)) | |
else: | |
txt = '%s year%s' % (day_diff/365, pluralize(day_diff/365)) | |
return format % txt |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment