| 100 | |
| 101 | def naturaltime(value, arg=None): |
| 102 | """ |
| 103 | For date and time values shows how many seconds, minutes or hours ago compared to |
| 104 | current timestamp returns representing string. Otherwise, returns a string |
| 105 | formatted according to settings.DATE_FORMAT |
| 106 | """ |
| 107 | try: |
| 108 | value = datetime(value.year, value.month, value.day, value.hour, value.minute, value.second) |
| 109 | except AttributeError: |
| 110 | return value |
| 111 | except ValueError: |
| 112 | return value |
| 113 | |
| 114 | delta = datetime.now() - value |
| 115 | if delta.days != 0: |
| 116 | value = date(value.year, value.month, value.day) |
| 117 | return naturalday(value, arg) |
| 118 | elif delta.seconds == 0: |
| 119 | return _(u'now') |
| 120 | elif delta.seconds < 60: |
| 121 | return _(u"%s seconds ago" % (delta.seconds)) |
| 122 | elif delta.seconds / 60 < 2: |
| 123 | return _(r'a minute ago') |
| 124 | elif delta.seconds / 60 < 60: |
| 125 | return _(u"%s minutes ago" % (delta.seconds/60)) |
| 126 | elif delta.seconds / 60 / 60 < 2: |
| 127 | return _(u'an hour ago') |
| 128 | elif delta.seconds / 60 / 60 < 24: |
| 129 | return _(u"%s hours ago" % (delta.seconds/60/60)) |
| 130 | return naturalday(value, arg) |
| 131 | register.filter(naturaltime) |