Some of the information here may be outdated, please check the book instead
[edit]

This is a port of the Django timesince function to web2py. To use it, put it in a model, controller or module. Or anywhere so that web2py sees it.

import datetime, time

def timesince(d, now=None):
    """
    Takes two datetime objects and returns the time between d and now
    as a nicely formatted string, e.g. "10 minutes".  If d occurs after now,
    then "0 minutes" is returned.

    Units used are years, months, weeks, days, hours, and minutes.
    Seconds and microseconds are ignored.  
    Up to two adjacent units will be displayed.  
    For example, 
    "2 weeks"              is legal 
    "1 year, 3 months"     is legal 

    but "1 year, 2 weeks"  is NOT legal
    because  "years" and "weeks" are NOT adjacent..... "months" has been skipped   

    Adapted from http://blog.natbat.co.uk/archive/2003/Jun/14/time_since
    """
    chunks = (
      (60 * 60 * 24 * 365, lambda n: T('one year') if n==1 else T('%(n)d years',dict(n=n))),
      (60 * 60 * 24 * 30, lambda n: T('one month') if n==1 else T('%(n)d months',dict(n=n))),
      (60 * 60 * 24 * 7, lambda n: T('one week') if n==1 else T('%(n)d weeks',dict(n=n))),
      (60 * 60 * 24, lambda n: T('one day') if n==1 else T('%(n)d days',dict(n=n))),
      (60 * 60, lambda n: T('one hour') if n==1 else T('%(n)d years',dict(n=n))),
      (60, lambda n: T('one minute') if n==1 else T('%(n)d minutes',dict(n=n))),
    )
    if not now:
        t = time.localtime()
        now = datetime.datetime(t[0], t[1], t[2], t[3], t[4], t[5])
    # ignore microsecond part of 'd' since we removed it from 'now'
    delta = now - (d - datetime.timedelta(0, 0, d.microsecond))
    since = delta.days * 24 * 60 * 60 + delta.seconds
    if since <= 0: return T('zero minutes')
    for seconds, name in chunks:
        count = since // seconds
        if count != 0: break
    return name(count)
© 2008-2010 by Massimo Di Pierro - All rights reserved - Powered by web2py - design derived from a theme by the earlybird
The content of this book is released under the Artistic License 2.0 - Modified content cannot be reproduced.