Python django.utils.timesince.timesince() Examples

The following are 30 code examples of django.utils.timesince.timesince(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.utils.timesince , or try the search function .
Example #1
Source File: models.py    From django-notify-x with MIT License 6 votes vote down vote up
def __str__(self):
        ctx = {
            'actor': self.actor or self.actor_text,
            'verb': self.verb,
            'description': self.description,
            'target': self.target or self.target_text,
            'obj': self.obj or self.obj_text,
            'at': timesince(self.created),
        }

        if ctx['actor']:
            if not ctx['target']:
                return _("{actor} {verb} {at} ago").format(**ctx)
            elif not ctx['obj']:
                return _("{actor} {verb} on {target} {at} ago").format(**ctx)
            elif ctx['obj']:
                return _(
                    "{actor} {verb} {obj} on {target} {at} ago").format(**ctx)
        return _("{description} -- {at} ago").format(**ctx) 
Example #2
Source File: test_timesince.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_other_units(self):
        """ Test other units. """
        self.assertEqual(timesince(self.t, self.t + self.oneminute), '1\xa0minute')
        self.assertEqual(timesince(self.t, self.t + self.onehour), '1\xa0hour')
        self.assertEqual(timesince(self.t, self.t + self.oneday), '1\xa0day')
        self.assertEqual(timesince(self.t, self.t + self.oneweek), '1\xa0week')
        self.assertEqual(timesince(self.t, self.t + self.onemonth), '1\xa0month')
        self.assertEqual(timesince(self.t, self.t + self.oneyear), '1\xa0year') 
Example #3
Source File: test_timesince.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_multiple_units(self):
        """ Test multiple units. """
        self.assertEqual(timesince(self.t, self.t + 2 * self.oneday + 6 * self.onehour), '2\xa0days, 6\xa0hours')
        self.assertEqual(timesince(self.t, self.t + 2 * self.oneweek + 2 * self.oneday), '2\xa0weeks, 2\xa0days') 
Example #4
Source File: test_timesince.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_display_first_unit(self):
        """
        If the two differing units aren't adjacent, only the first unit is
        displayed.
        """
        self.assertEqual(
            timesince(self.t, self.t + 2 * self.oneweek + 3 * self.onehour + 4 * self.oneminute),
            '2\xa0weeks'
        )
        self.assertEqual(timesince(self.t, self.t + 4 * self.oneday + 5 * self.oneminute), '4\xa0days') 
Example #5
Source File: test_timesince.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_different_timezones(self):
        """ When using two different timezones. """
        now = datetime.datetime.now()
        now_tz = timezone.make_aware(now, timezone.get_default_timezone())
        now_tz_i = timezone.localtime(now_tz, timezone.get_fixed_timezone(195))

        self.assertEqual(timesince(now), '0\xa0minutes')
        self.assertEqual(timesince(now_tz), '0\xa0minutes')
        self.assertEqual(timesince(now_tz_i), '0\xa0minutes')
        self.assertEqual(timesince(now_tz, now_tz_i), '0\xa0minutes')
        self.assertEqual(timeuntil(now), '0\xa0minutes')
        self.assertEqual(timeuntil(now_tz), '0\xa0minutes')
        self.assertEqual(timeuntil(now_tz_i), '0\xa0minutes')
        self.assertEqual(timeuntil(now_tz, now_tz_i), '0\xa0minutes') 
Example #6
Source File: test_timesince.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_date_objects(self):
        """ Both timesince and timeuntil should work on date objects (#17937). """
        today = datetime.date.today()
        self.assertEqual(timesince(today + self.oneday), '0\xa0minutes')
        self.assertEqual(timeuntil(today - self.oneday), '0\xa0minutes') 
Example #7
Source File: test_timesince.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_leap_year(self):
        start_date = datetime.date(2016, 12, 25)
        self.assertEqual(timeuntil(start_date + self.oneweek, start_date), '1\xa0week')
        self.assertEqual(timesince(start_date, start_date + self.oneweek), '1\xa0week') 
Example #8
Source File: test_timesince.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_leap_year_new_years_eve(self):
        t = datetime.date(2016, 12, 31)
        now = datetime.datetime(2016, 12, 31, 18, 0, 0)
        self.assertEqual(timesince(t + self.oneday, now), '0\xa0minutes')
        self.assertEqual(timeuntil(t - self.oneday, now), '0\xa0minutes') 
Example #9
Source File: test_timesince.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_naive_datetime_with_tzinfo_attribute(self):
        class naive(datetime.tzinfo):
            def utcoffset(self, dt):
                return None
        future = datetime.datetime(2080, 1, 1, tzinfo=naive())
        self.assertEqual(timesince(future), '0\xa0minutes')
        past = datetime.datetime(1980, 1, 1, tzinfo=naive())
        self.assertEqual(timeuntil(past), '0\xa0minutes') 
Example #10
Source File: test_timesince.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_equal_datetimes(self):
        """ equal datetimes. """
        # NOTE: \xa0 avoids wrapping between value and unit
        self.assertEqual(timesince(self.t, self.t), '0\xa0minutes') 
Example #11
Source File: test_timesince.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_ignore_microseconds_and_seconds(self):
        """ Microseconds and seconds are ignored. """
        self.assertEqual(timesince(self.t, self.t + self.onemicrosecond), '0\xa0minutes')
        self.assertEqual(timesince(self.t, self.t + self.onesecond), '0\xa0minutes') 
Example #12
Source File: test_timesince.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_other_units(self):
        """ Test other units. """
        self.assertEqual(timesince(self.t, self.t + self.oneminute), '1\xa0minute')
        self.assertEqual(timesince(self.t, self.t + self.onehour), '1\xa0hour')
        self.assertEqual(timesince(self.t, self.t + self.oneday), '1\xa0day')
        self.assertEqual(timesince(self.t, self.t + self.oneweek), '1\xa0week')
        self.assertEqual(timesince(self.t, self.t + self.onemonth), '1\xa0month')
        self.assertEqual(timesince(self.t, self.t + self.oneyear), '1\xa0year') 
Example #13
Source File: test_timesince.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_multiple_units(self):
        """ Test multiple units. """
        self.assertEqual(timesince(self.t, self.t + 2 * self.oneday + 6 * self.onehour), '2\xa0days, 6\xa0hours')
        self.assertEqual(timesince(self.t, self.t + 2 * self.oneweek + 2 * self.oneday), '2\xa0weeks, 2\xa0days') 
Example #14
Source File: test_timesince.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_display_first_unit(self):
        """
        If the two differing units aren't adjacent, only the first unit is
        displayed.
        """
        self.assertEqual(
            timesince(self.t, self.t + 2 * self.oneweek + 3 * self.onehour + 4 * self.oneminute),
            '2\xa0weeks'
        )
        self.assertEqual(timesince(self.t, self.t + 4 * self.oneday + 5 * self.oneminute), '4\xa0days') 
Example #15
Source File: test_timesince.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_different_timezones(self):
        """ When using two different timezones. """
        now = datetime.datetime.now()
        now_tz = timezone.make_aware(now, timezone.get_default_timezone())
        now_tz_i = timezone.localtime(now_tz, timezone.get_fixed_timezone(195))

        self.assertEqual(timesince(now), '0\xa0minutes')
        self.assertEqual(timesince(now_tz), '0\xa0minutes')
        self.assertEqual(timesince(now_tz_i), '0\xa0minutes')
        self.assertEqual(timesince(now_tz, now_tz_i), '0\xa0minutes')
        self.assertEqual(timeuntil(now), '0\xa0minutes')
        self.assertEqual(timeuntil(now_tz), '0\xa0minutes')
        self.assertEqual(timeuntil(now_tz_i), '0\xa0minutes')
        self.assertEqual(timeuntil(now_tz, now_tz_i), '0\xa0minutes') 
Example #16
Source File: test_timesince.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_date_objects(self):
        """ Both timesince and timeuntil should work on date objects (#17937). """
        today = datetime.date.today()
        self.assertEqual(timesince(today + self.oneday), '0\xa0minutes')
        self.assertEqual(timeuntil(today - self.oneday), '0\xa0minutes') 
Example #17
Source File: test_timesince.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_leap_year(self):
        start_date = datetime.date(2016, 12, 25)
        self.assertEqual(timeuntil(start_date + self.oneweek, start_date), '1\xa0week')
        self.assertEqual(timesince(start_date, start_date + self.oneweek), '1\xa0week') 
Example #18
Source File: test_timesince.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_leap_year_new_years_eve(self):
        t = datetime.date(2016, 12, 31)
        now = datetime.datetime(2016, 12, 31, 18, 0, 0)
        self.assertEqual(timesince(t + self.oneday, now), '0\xa0minutes')
        self.assertEqual(timeuntil(t - self.oneday, now), '0\xa0minutes') 
Example #19
Source File: test_timesince.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_naive_datetime_with_tzinfo_attribute(self):
        class naive(datetime.tzinfo):
            def utcoffset(self, dt):
                return None
        future = datetime.datetime(2080, 1, 1, tzinfo=naive())
        self.assertEqual(timesince(future), '0\xa0minutes')
        past = datetime.datetime(1980, 1, 1, tzinfo=naive())
        self.assertEqual(timeuntil(past), '0\xa0minutes') 
Example #20
Source File: filters.py    From django_twitter with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def time_difference(value):
    now = datetime.utcnow().replace(tzinfo=utc)
    try:
        difference = now - value
    except:
        return value

    if difference <= timedelta(minutes=1):
        return 'Just now'
    return '%(time)s ago' % {'time': timesince(value).split(', ')[0]} 
Example #21
Source File: defaultfilters.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def timesince_filter(value, arg=None):
    """Formats a date as the time since that date (i.e. "4 days, 6 hours")."""
    if not value:
        return ''
    try:
        if arg:
            return timesince(value, arg)
        return timesince(value)
    except (ValueError, TypeError):
        return '' 
Example #22
Source File: defaultfilters.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def timesince_filter(value, arg=None):
    """Formats a date as the time since that date (i.e. "4 days, 6 hours")."""
    if not value:
        return ''
    try:
        if arg:
            return timesince(value, arg)
        return timesince(value)
    except (ValueError, TypeError):
        return '' 
Example #23
Source File: panels.py    From django-cachalot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def nav_subtitle(self):
        if self.enabled and self.last_invalidation is not None:
            return (_('Last invalidation: %s')
                    % timesince(self.last_invalidation))
        return '' 
Example #24
Source File: views.py    From casepro with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get(self, request, *args, **kwargs):
            org = self.request.org
            user = self.request.user
            page = int(self.request.GET.get("page", 1))

            search = self.derive_search()
            items = Outgoing.search_replies(org, user, search)

            paginator = LazyPaginator(items, 50)
            outgoing = paginator.page(page)
            has_more = paginator.num_pages > page

            def as_json(msg):
                delay = (msg.created_on - msg.reply_to.created_on).total_seconds()
                obj = msg.as_json()
                obj.update(
                    {
                        "reply_to": {
                            "text": msg.reply_to.text,
                            "flagged": msg.reply_to.is_flagged,
                            "labels": [l.as_json(full=False) for l in msg.reply_to.labels.all()],
                        },
                        "response": {
                            "delay": timesince(msg.reply_to.created_on, now=msg.created_on),
                            "warning": delay > RESPONSE_DELAY_WARN_SECONDS,
                        },
                    }
                )
                return obj

            return JsonResponse({"results": [as_json(o) for o in outgoing], "has_more": has_more}, encoder=JSONEncoder) 
Example #25
Source File: defaultfilters.py    From bioforum with MIT License 5 votes vote down vote up
def timesince_filter(value, arg=None):
    """Format a date as the time since that date (i.e. "4 days, 6 hours")."""
    if not value:
        return ''
    try:
        if arg:
            return timesince(value, arg)
        return timesince(value)
    except (ValueError, TypeError):
        return '' 
Example #26
Source File: __init__.py    From zulip with Apache License 2.0 5 votes vote down vote up
def environment(**options: Any) -> Environment:
    env = Environment(**options)
    env.globals.update({
        'default_page_params': {
            'debug_mode': False,
            'webpack_public_path': staticfiles_storage.url(
                settings.WEBPACK_LOADER['DEFAULT']['BUNDLE_DIR_NAME'],
            ),
        },
        'static': staticfiles_storage.url,
        'url': reverse,
        'render_markdown_path': render_markdown_path,
    })

    env.install_gettext_translations(translation, True)

    env.filters['slugify'] = slugify
    env.filters['pluralize'] = pluralize
    env.filters['display_list'] = display_list
    env.filters['device_action'] = device_action
    env.filters['timesince'] = timesince

    return env 
Example #27
Source File: views.py    From zulip with Apache License 2.0 5 votes vote down vote up
def get_confirmations(types: List[int], object_ids: List[int],
                      hostname: Optional[str]=None) -> List[Dict[str, Any]]:
    lowest_datetime = timezone_now() - timedelta(days=30)
    confirmations = Confirmation.objects.filter(type__in=types, object_id__in=object_ids,
                                                date_sent__gte=lowest_datetime)
    confirmation_dicts = []
    for confirmation in confirmations:
        realm = confirmation.realm
        content_object = confirmation.content_object

        type = confirmation.type
        days_to_activate = _properties[type].validity_in_days
        expiry_date = confirmation.date_sent + timedelta(days=days_to_activate)

        if hasattr(content_object, "status"):
            if content_object.status == STATUS_ACTIVE:
                link_status = "Link has been clicked"
            else:
                link_status = "Link has never been clicked"
        else:
            link_status = ""

        if timezone_now() < expiry_date:
            expires_in = timesince(confirmation.date_sent, expiry_date)
        else:
            expires_in = "Expired"

        url = confirmation_url(confirmation.confirmation_key, realm, type)
        confirmation_dicts.append({"object": confirmation.content_object,
                                   "url": url, "type": type, "link_status": link_status,
                                   "expires_in": expires_in})
    return confirmation_dicts 
Example #28
Source File: models.py    From Collaboration-System with GNU General Public License v2.0 5 votes vote down vote up
def timesince(self, now=None):
        """
        Shortcut for the ``django.utils.timesince.timesince`` function of the
        current timestamp.
        """
        from django.utils.timesince import timesince as timesince_
        return timesince_(self.timestamp, now) 
Example #29
Source File: defaultfilters.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def timesince_filter(value, arg=None):
    """Format a date as the time since that date (i.e. "4 days, 6 hours")."""
    if not value:
        return ''
    try:
        if arg:
            return timesince(value, arg)
        return timesince(value)
    except (ValueError, TypeError):
        return '' 
Example #30
Source File: defaultfilters.py    From python with Apache License 2.0 5 votes vote down vote up
def timesince_filter(value, arg=None):
    """Formats a date as the time since that date (i.e. "4 days, 6 hours")."""
    if not value:
        return ''
    try:
        if arg:
            return timesince(value, arg)
        return timesince(value)
    except (ValueError, TypeError):
        return ''