proper order of status updates in storing list
[minibook.git] / timesince.py
blob9ae69b574bda42625d3bac52876d91f2cd9f9cdc
1 #!/usr/bin/python
3 import time
6 # Adapted from
7 # http://code.djangoproject.com/browser/django/trunk/django/utils/timesince.py
8 # Modified that it takes GMT-zone UNIX time in seconds
10 def pluralize(singular, plural, count):
11 if count == 1:
12 return singular
13 else:
14 return plural
17 def timesince(d, now=None):
18 """
19 Takes two datetime objects and returns the time between then and now
20 as a nicely formatted string, e.g "10 minutes"
21 Adapted from http://blog.natbat.co.uk/archive/2003/Jun/14/time_since
22 (Can check it in the Internet Archive)
23 """
24 chunks = (
25 (60 * 60 * 24 * 365, lambda n: pluralize('year', 'years', n)),
26 (60 * 60 * 24 * 30, lambda n: pluralize('month', 'months', n)),
27 (60 * 60 * 24 * 7, lambda n: pluralize('week', 'weeks', n)),
28 (60 * 60 * 24, lambda n: pluralize('day', 'days', n)),
29 (60 * 60, lambda n: pluralize('hour', 'hours', n)),
30 (60, lambda n: pluralize('minute', 'minutes', n)))
31 # Convert time to UNIX seconds format for comparison
32 if d.__class__ is not int:
33 d = int(d)
34 if not now:
35 now = int(time.time())
37 since = now - d
38 if since <= 0:
39 return 'moments'
41 for i, (seconds, name) in enumerate(chunks):
42 count = since / seconds
43 if count != 0:
44 break
46 if count <= 0:
47 return 'less then a minute'
49 s = '%d %s' % (count, name(count))
50 if i + 1 < len(chunks):
51 # Now get the second item
52 seconds2, name2 = chunks[i + 1]
53 count2 = (since - (seconds * count)) / seconds2
54 if count2 != 0:
55 s += ', %d %s' % (count2, name2(count2))
56 return s
59 def timeuntil(d, now=None):
60 """
61 Like timesince, but returns a string measuring the time until
62 the given time.
63 """
64 if now == None:
65 now = int(time.time())
66 return timesince(now, d)