Flask Snippets

Snippets are unofficial and unmaintained.

This is an archived view of user-submitted snippets. Despite being hosted on the Flask site, they are not official. No Flask maintainer has curated or checked the snippets for security, correctness, or design.

timesince filter

Posted by Dan Jacob on 2010-07-13 @ 10:45 and filed in Template Tricks

This is a filter that takes a datetime instance and returns a "time since" string. For example, "3 minutes ago" or "4 weeks ago":

from datetime import datetime

@app.template_filter()
def timesince(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

Further enhancement would include localization support for the various strings and a "timeuntil" filter that returns e.g. "3 minutes from now".

This snippet by Dan Jacob can be used freely for anything you like. Consider it public domain.

Comments