~jconti/recent-notifications/trunk

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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
"""
Timestamp.py
by Jason Conti
March 15, 2010

Functions for working with timestamps.
"""

import locale

from datetime import datetime

from Translations import _, ngettext

def now():
  """Returns a datetime objects with the current timestamp."""
  return datetime.now()

def locale_date(timestamp):
  """Returns a string with the date in the current locales format."""
  return timestamp.strftime(locale.nl_langinfo(locale.D_FMT))

def locale_datetime(timestamp):
  """Returns a string with the date and time in the current locales format."""
  return timestamp.strftime(locale.nl_langinfo(locale.D_T_FMT))

def locale_time(timestamp):
  """Returns a string with the time in the current locales format."""
  return timestamp.strftime(locale.nl_langinfo(locale.T_FMT))

def time_ago_in_words(timestamp):
  """Returns a string in a format such as "less than a minute ago" or "2 hours ago"
  the distance in time from timestamp to now. If the difference is more than
  a day, returns locale_datetime instead."""
  delta = now() - timestamp
  s = delta.seconds
  m = s / 60
  h = m / 60
  d = delta.days

  if d < 1:
    # Seconds
    if s < 60:
      return _("less than a minute ago")
    # Minutes
    elif m < 60:
      return ngettext("1 minute ago", "{0} minutes ago", m).format(m)
    # Hours
    else:
      return ngettext("1 hour ago", "{0} hours ago", h).format(h)

  # Greater than a day
  else:
    return locale_datetime(timestamp)