15
15
# along with this program; if not, write to the Free Software
16
16
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
# Module: Date utilities
19
# Author: William Grant
18
'''Utilities for making nice, human readable dates.'''
24
seconds_per_day = 86400 # 60 * 60 * 24
26
timezone_offset = time.altzone
28
timezone_offset = time.timezone
30
def make_date_nice(seconds_since_epoch):
31
"""Given a number of seconds elapsed since the epoch,
23
def get_datetime(datetime_or_seconds):
24
'''Return the given datetime, or convert the given seconds since epoch.'''
25
if type(datetime_or_seconds) is datetime.datetime:
26
return datetime_or_seconds
27
return datetime.datetime.fromtimestamp(datetime_or_seconds)
29
def make_date_nice(datetime_or_seconds):
30
"""Generate a full human-readable representation of a date and time.
32
Given a datetime or number of seconds elapsed since the epoch,
32
33
generates a string representing the date/time in human-readable form.
33
34
"ddd mmm dd, yyyy h:m a"
35
#return time.ctime(seconds_since_epoch)
36
return time.strftime("%a %b %d %Y, %I:%M %p",
37
time.localtime(seconds_since_epoch))
39
def make_date_nice_short(seconds_since_epoch):
40
"""Given a number of seconds elapsed since the epoch,
36
dt = get_datetime(datetime_or_seconds)
37
return dt.strftime("%a %b %d %Y, %I:%M %p")
39
def make_date_nice_short(datetime_or_seconds):
40
"""Generate a very compact human-readable representation of a date.
42
Given a datetime or number of seconds elapsed since the epoch,
41
43
generates a string representing the date in human-readable form.
42
44
Does not include the time.
43
This function generates a very compact representation."""
47
dt = get_datetime(datetime_or_seconds)
48
now = datetime.datetime.now()
44
50
# Use a "naturalisation" algorithm.
45
days_ago = (int(time.time() - timezone_offset) / seconds_per_day
46
- int(seconds_since_epoch - timezone_offset) / seconds_per_day)
48
54
# Dates today or yesterday, return "today" or "yesterday".
54
return str(days_ago) + " days ago"
55
# Dates in the last 5 days, return "n days ago".
60
# Dates in the last 5 days, return "n days ago".
61
return str(delta.days) + " days ago"
56
62
# Other dates, return a short date format.
57
63
# If within the same year, omit the year (mmm dd)
58
if time.localtime(seconds_since_epoch).tm_year==time.localtime().tm_year:
59
return time.strftime("%b %d", time.localtime(seconds_since_epoch))
64
if dt.year == now.year:
65
return dt.strftime("%b %d")
60
66
# Else, include the year (mmm dd, yyyy)
62
return time.strftime("%b %d, %Y", time.localtime(seconds_since_epoch))
68
return dt.strftime("%b %d, %Y")