License New BSD license
Lines 46
Keywords
datetime (2) pretty print (3) Pylons (10) time zones (1)
Permissions
Owner: Stou S.
Viewable by Everyone
Editable by All Siafoo Users
Hide
Siafoo is here to make coding less frustrating and to save you time. Join Siafoo Now or Learn More

Distance of time in words Atom Feed 0

In Brief This a slightly modified version of the distance_of_time_in_words method found in the Pylons WebHelpers module. The modification is that the method will now use datetime objects natively and allows for timezones.
# 's
 1from datetime import datetime
2
3def age(from_date, since_date = None, target_tz=None, include_seconds=False):
4 '''
5 Returns the age as a string
6 '''
7
8 if since_date is None:
9 since_date = datetime.now(target_tz)
10
11 distance_in_time = since_date - from_date
12 distance_in_seconds = int(round(abs(distance_in_time.days * 86400 + distance_in_time.seconds)))
13 distance_in_minutes = int(round(distance_in_seconds/60))
14
15 if distance_in_minutes <= 1:
16 if include_seconds:
17 for remainder in [5, 10, 20]:
18 if distance_in_seconds < remainder:
19 return "less than %s seconds" % remainder
20 if distance_in_seconds < 40:
21 return "half a minute"
22 elif distance_in_seconds < 60:
23 return "less than a minute"
24 else:
25 return "1 minute"
26 else:
27 if distance_in_minutes == 0:
28 return "less than a minute"
29 else:
30 return "1 minute"
31 elif distance_in_minutes < 45:
32 return "%s minutes" % distance_in_minutes
33 elif distance_in_minutes < 90:
34 return "about 1 hour"
35 elif distance_in_minutes < 1440:
36 return "about %d hours" % (round(distance_in_minutes / 60.0))
37 elif distance_in_minutes < 2880:
38 return "1 day"
39 elif distance_in_minutes < 43220:
40 return "%d days" % (round(distance_in_minutes / 1440))
41 elif distance_in_minutes < 86400:
42 return "about 1 month"
43 elif distance_in_minutes < 525600:
44 return "%d months" % (round(distance_in_minutes / 43200))
45 elif distance_in_minutes < 1051200:
46 return "about 1 year"
47 else:
48 return "over %d years" % (round(distance_in_minutes / 525600))

This a slightly modified version of the distance_of_time_in_words method found in the Pylons WebHelpers module. The modification is that the method will now use datetime objects natively and allows for timezones.