Project

General

Profile

Download (1.18 KB) Statistics
| Branch: | Tag: | Revision:

root / entrouvert / djommon / humantime / utils.py @ 954ab988

1
import datetime
2

    
3
from django.utils.translation import npgettext, pgettext
4

    
5
def datetime2human(dt, include_time=False, days_limit=7):
6
    '''Format a datetime object for human consumption'''
7
    if isinstance(dt, datetime.datetime):
8
        time = dt.strftime('%H:%M')
9
    else:
10
        dt = datetime.datetime(year=dt.year, month=dt.month, day=dt.day)
11
        include_time = False
12
    today = datetime.date.today()
13
    yesterday = today - datetime.timedelta(days=1)
14
    date = dt.date()
15
    if date == today:
16
        if include_time:
17
            return pgettext('humantime', 'today at {0}').format(time)
18
        else:
19
            return pgettext('humantime', 'today')
20
    elif date == yesterday:
21
        if include_time:
22
            return pgettext('humantime', 'yesterday at {0}').format(time)
23
        else:
24
            return pgettext('humantime', 'yesterday')
25
    else:
26
        delta = (today - date).days
27
        if delta <= days_limit:
28
            return npgettext('humantime', '{0} day ago', '{0} days ago',
29
                    delta).format(delta)
30
        else:
31
            return npgettext('humantime', 'more than {0} day ago', 'more than {0} days ago',
32
                    days_limit).format(days_limit)
(3-3/3)