If you benefit from web2py hope you feel encouraged to pay it forward by contributing back to society in whatever form you choose!
#!/usr/bin/env python
# coding: utf8

from gluon.html import *
from gluon.http import *
from gluon.validators import *
from gluon.sqlhtml import *

from gluon import current

import datetime

# This module is a integration to web2py in order to allow use of magic T()
# By : Richard Vézina
# Original library : ago
# From : Russell Ballestrini
# Repository : https://bitbucket.org/russellballestrini/ago/src
# Ex.:
# In your controller add this :
# from ago import human
# You can use it in a represent like this :
# db.table_name.field_name.represent = lambda value, row: human(value.replace(tzinfo=None)) if value else T('N/A')
# Notice : tzinfo is not supported actually
# For further example and representation tweaks, you can read the test file of ago lib here :
# https://bitbucket.org/russellballestrini/ago/src/57d0c33e2a5ef92ddf14017ab71ce1129084d885/test_ago.py?at=default

def delta2dict(delta):
    """Accepts a delta, returns a dictionary of units"""
    delta = abs(delta)
    return {'year': delta.days / 365,
            'day': delta.days % 365,
            'hour': delta.seconds / 3600,
            'minute': (delta.seconds / 60) % 60,
            'second': delta.seconds % 60,
            'microsecond': delta.microseconds
            }


def human(dt, precision=2, past_tense='{} ago', future_tense='in {}'):
    """Accept a datetime or timedelta, return a human readable delta string"""
    delta = dt
    if type(dt) is not type(datetime.timedelta()):
        delta = datetime.datetime.now() - dt

    the_tense = past_tense
    if delta < datetime.timedelta(0):
        the_tense = future_tense

    d = delta2dict(delta)
    hlist = []
    count = 0
    units = ('year', 'day', 'hour', 'minute', 'second', 'microsecond')
    for unit in units:
        if count >= precision: break  # met precision
        if d[unit] == 0: continue  # skip 0's
        s = '' if d[unit] == 1 else 's'  # handle plurals
        hlist.append('%s %s%s' % (d[unit], current.T(unit), s))
        count += 1
    human_delta = ', '.join(hlist)
    return the_tense.format(human_delta)

Related slices

Comments (1)

  • Login to post



  • 0
    niphlod 10 years ago

    there's prettydate that does the exact same thing already included. What is missing ?

    replies (1)
    • mlrichardvezina 10 years ago

      Notting... I just didn't know it!

      Though ago.py is nice too... Maybe in contrib it has his place!! So if someone want a different way of representing timestamp...

      :)

      Richard


Hosting graciously provided by:
Python Anywhere