~jconti/recent-notifications/trunk

« back to all changes in this revision

Viewing changes to unity/Timestamp.py

  • Committer: Jason Conti
  • Date: 2011-03-26 21:20:00 UTC
  • Revision ID: jason.conti@gmail.com-20110326212000-48rj1zased29tne4
Ported Notification.py to gobject introspection, everything except dbus. Going to attempt that next, but may revert if it doesn't work so well yet.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
"""
 
2
Timestamp.py
 
3
by Jason Conti
 
4
March 15, 2010
 
5
updated: March 26, 2011
 
6
 
 
7
Functions for working with timestamps.
 
8
"""
 
9
 
 
10
import locale
 
11
 
 
12
from datetime import datetime
 
13
 
 
14
from Translations import _, ngettext
 
15
 
 
16
def now():
 
17
  """Returns a datetime objects with the current timestamp."""
 
18
  return datetime.now()
 
19
 
 
20
def locale_date(timestamp):
 
21
  """Returns a string with the date in the current locales format."""
 
22
  return timestamp.strftime(locale.nl_langinfo(locale.D_FMT))
 
23
 
 
24
def locale_datetime(timestamp):
 
25
  """Returns a string with the date and time in the current locales format."""
 
26
  return timestamp.strftime(locale.nl_langinfo(locale.D_T_FMT))
 
27
 
 
28
def locale_time(timestamp):
 
29
  """Returns a string with the time in the current locales format."""
 
30
  return timestamp.strftime(locale.nl_langinfo(locale.T_FMT))
 
31
 
 
32
def time_ago_in_words(timestamp):
 
33
  """Returns a string in a format such as "less than a minute ago" or "2 hours ago"
 
34
  the distance in time from timestamp to now. If the difference is more than
 
35
  a day, returns locale_datetime instead."""
 
36
  delta = now() - timestamp
 
37
  s = delta.seconds
 
38
  m = s / 60
 
39
  h = m / 60
 
40
  d = delta.days
 
41
 
 
42
  if d < 1:
 
43
    # Seconds
 
44
    if s < 60:
 
45
      return _("less than a minute ago")
 
46
    # Minutes
 
47
    elif m < 60:
 
48
      return ngettext("1 minute ago", "{0} minutes ago", m).format(m)
 
49
    # Hours
 
50
    else:
 
51
      return ngettext("1 hour ago", "{0} hours ago", h).format(h)
 
52
 
 
53
  # Greater than a day
 
54
  else:
 
55
    return locale_datetime(timestamp)
 
56