humanize time difference (how long ago)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
def humanizeTimeDiff(timestamp = None):
    """
    Returns a humanized string representing time difference
    between now() and the input timestamp.
    
    The output rounds up to days, hours, minutes, or seconds.
    4 days 5 hours returns '4 days'
    0 days 4 hours 3 minutes returns '4 hours', etc...
    """
    import datetime
    
    timeDiff = datetime.datetime.now() - timestamp
    days = timeDiff.days
    hours = timeDiff.seconds/3600
    minutes = timeDiff.seconds%3600/60
    seconds = timeDiff.seconds%3600%60
    
    str = ""
    tStr = ""
    if days > 0:
        if days == 1:   tStr = "day"
        else:           tStr = "days"
        str = str + "%s %s" %(days, tStr)
        return str
    elif hours > 0:
        if hours == 1:  tStr = "hour"
        else:           tStr = "hours"
        str = str + "%s %s" %(hours, tStr)
        return str
    elif minutes > 0:
        if minutes == 1:tStr = "min"
        else:           tStr = "mins"           
        str = str + "%s %s" %(minutes, tStr)
        return str
    elif seconds > 0:
        if seconds == 1:tStr = "sec"
        else:           tStr = "secs"
        str = str + "%s %s" %(seconds, tStr)
        return str
    else:
        return None

More like this

  1. Fuzzy Date Diff Template Filter by zain 5 years, 1 month ago
  2. Timedelta template tag by dballanc 6 years, 12 months ago
  3. Optimized humanize naturalday filter by c2j 4 years, 7 months ago
  4. Smart i18n date diff (twitter like) by Batiste 5 years ago
  5. Timing Django Requests by metajack 5 years, 10 months ago

Comments

dballanc (on September 11, 2007):

It is different. It's a 'fuzzy' ouput. Timesince give you '3 days, 1 hour ago'. This would just give you '3days'.

#

tupopo (on September 29, 2007):

can somebody tell me how to use it? i added these code at the begining: from django import template

register = template.Library()

@register.filter

and then used it in the template as: {% commrate.time|humanizetimediff %}

thanks!

#

(Forgotten your password?)