Created
July 16, 2016 12:39
-
-
Save selfboot/1f620c58ba4eb65165bfd96c8dbfa88d to your computer and use it in GitHub Desktop.
Returns string representing "time since", 3 days ago, 5 hours ago etc. For datetime values, returns a string representing how many seconds, minutes or hours ago it was – falling back to the timesince format if the value is more than a day old.
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
| from datetime import datetime | |
| @app.template_filter() | |
| def natural_time(dt, default="just now"): | |
| """ | |
| Returns string representing "time since" e.g. | |
| 3 days ago, 5 hours ago etc. | |
| """ | |
| now = datetime.utcnow() | |
| diff = now - dt | |
| periods = ( | |
| (diff.days / 365, "year", "years"), | |
| (diff.days / 30, "month", "months"), | |
| (diff.days / 7, "week", "weeks"), | |
| (diff.days, "day", "days"), | |
| (diff.seconds / 3600, "hour", "hours"), | |
| (diff.seconds / 60, "minute", "minutes"), | |
| (diff.seconds, "second", "seconds"), | |
| ) | |
| for period, singular, plural in periods: | |
| if period: | |
| return "%d %s ago" % (period, singular if period == 1 else plural) | |
| return default |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment