from math import fabs
from datetime import datetime


def pretty_date(d):
    """
    Format the time delta between d and now human-friendly. E.g. 'in 2 hours', '20 seconds ago'
    :param d:
    :return:
    """

    now = datetime.now()
    diff = now - d
    total_seconds = diff.seconds + diff.days * 24 * 60 * 60
    sec = int(fabs(total_seconds))

    if sec < 60:
        v = sec
        unit = 'second' + ('s' if v != 1 else '')
    elif sec < 60 * 60:
        v = sec / 60
        unit = 'minute' + ('s' if v != 1 else '')
    elif sec < 60 * 60 * 24:
        v = sec / 60 / 60
        unit = 'hour' + ('s' if v != 1 else '')
    else:
        v = sec / 60 / 60 / 24
        unit = 'day' + ('s' if v != 1 else '')

    if total_seconds < 0:
        return 'in %i %s' % (v, unit)  # future
    else:
        return '%i %s ago' % (v, unit)