當前位置: 首頁>>代碼示例>>Python>>正文


Python humanize.naturaltime方法代碼示例

本文整理匯總了Python中django.contrib.humanize.templatetags.humanize.naturaltime方法的典型用法代碼示例。如果您正苦於以下問題:Python humanize.naturaltime方法的具體用法?Python humanize.naturaltime怎麽用?Python humanize.naturaltime使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在django.contrib.humanize.templatetags.humanize的用法示例。


在下文中一共展示了humanize.naturaltime方法的14個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: relative_date

# 需要導入模塊: from django.contrib.humanize.templatetags import humanize [as 別名]
# 或者: from django.contrib.humanize.templatetags.humanize import naturaltime [as 別名]
def relative_date(value):
    if value in ('', None):
        return ''

    current = timezone.now()
    
    if (current - value) > timedelta(days=1):
        return date(value, "SHORT_DATETIME_FORMAT")
        
    return naturaltime(value) 
開發者ID:fpsw,項目名稱:Servo,代碼行數:12,代碼來源:servo_tags.py

示例2: display_time_str

# 需要導入模塊: from django.contrib.humanize.templatetags import humanize [as 別名]
# 或者: from django.contrib.humanize.templatetags.humanize import naturaltime [as 別名]
def display_time_str(d):
    #return d.strftime('%H:%M:%S %m/%d/%y')
    return naturaltime(d) 
開發者ID:idaholab,項目名稱:civet,代碼行數:5,代碼來源:TimeUtils.py

示例3: human_time_str

# 需要導入模塊: from django.contrib.humanize.templatetags import humanize [as 別名]
# 或者: from django.contrib.humanize.templatetags.humanize import naturaltime [as 別名]
def human_time_str(d):
    #return d.strftime('%H:%M:%S %m/%d/%y')
    return naturaltime(d) 
開發者ID:idaholab,項目名稱:civet,代碼行數:5,代碼來源:TimeUtils.py

示例4: get_created_naturaltime

# 需要導入模塊: from django.contrib.humanize.templatetags import humanize [as 別名]
# 或者: from django.contrib.humanize.templatetags.humanize import naturaltime [as 別名]
def get_created_naturaltime(self, obj):
        """Returns human readable time."""
        return naturaltime(obj.created) 
開發者ID:thetruefuss,項目名稱:elmer,代碼行數:5,代碼來源:serializers.py

示例5: get_data_naturaltime

# 需要導入模塊: from django.contrib.humanize.templatetags import humanize [as 別名]
# 或者: from django.contrib.humanize.templatetags.humanize import naturaltime [as 別名]
def get_data_naturaltime(self, obj):
        """
        Returns human readable time.

        :return: string
        """
        return naturaltime(obj.date) 
開發者ID:thetruefuss,項目名稱:elmer,代碼行數:9,代碼來源:serializers.py

示例6: json_serial

# 需要導入模塊: from django.contrib.humanize.templatetags import humanize [as 別名]
# 或者: from django.contrib.humanize.templatetags.humanize import naturaltime [as 別名]
def json_serial(obj):
    """JSON serializer for objects not serializable by default json code"""

    if isinstance(obj, datetime):
        serial = naturaltime(obj)
        return serial
    raise TypeError('Type not serializable') 
開發者ID:OpenBankProject,項目名稱:API-Manager,代碼行數:9,代碼來源:utils.py

示例7: get_relative_rated_at

# 需要導入模塊: from django.contrib.humanize.templatetags import humanize [as 別名]
# 或者: from django.contrib.humanize.templatetags.humanize import naturaltime [as 別名]
def get_relative_rated_at(self, obj):
        return naturaltime(obj.rated_at) 
開發者ID:nextcloud,項目名稱:appstore,代碼行數:4,代碼來源:serializers.py

示例8: get

# 需要導入模塊: from django.contrib.humanize.templatetags import humanize [as 別名]
# 或者: from django.contrib.humanize.templatetags.humanize import naturaltime [as 別名]
def get(self, request) :
        strval =  request.GET.get("search", False)
        if strval :
            # Simple title-only search
            # objects = Post.objects.filter(title__contains=strval).select_related().order_by('-updated_at')[:10]

            # Multi-field search
            query = Q(title__contains=strval)
            query.add(Q(text__contains=strval), Q.OR)
            objects = Post.objects.filter(query).select_related().order_by('-updated_at')[:10]
        else :
            # try both versions with > 4 posts and watch the queries that happen
            objects = Post.objects.all().order_by('-updated_at')[:10]
            # objects = Post.objects.select_related().all().order_by('-updated_at')[:10]

        # Augment the post_list
        for obj in objects:
            obj.natural_updated = naturaltime(obj.updated_at)

        ctx = {'post_list' : objects, 'search': strval}
        retval = render(request, self.template_name, ctx)

        dump_queries()
        return retval;

# References

# https://docs.djangoproject.com/en/3.0/topics/db/queries/#one-to-many-relationships

# Note that the select_related() QuerySet method recursively prepopulates the
# cache of all one-to-many relationships ahead of time.

# sql “LIKE” equivalent in django query
# https://stackoverflow.com/questions/18140838/sql-like-equivalent-in-django-query

# How do I do an OR filter in a Django query?
# https://stackoverflow.com/questions/739776/how-do-i-do-an-or-filter-in-a-django-query

# https://stackoverflow.com/questions/1074212/how-can-i-see-the-raw-sql-queries-django-is-running 
開發者ID:csev,項目名稱:dj4e-samples,代碼行數:41,代碼來源:views.py

示例9: get

# 需要導入模塊: from django.contrib.humanize.templatetags import humanize [as 別名]
# 或者: from django.contrib.humanize.templatetags.humanize import naturaltime [as 別名]
def get(self, request):
        messages = Message.objects.all().order_by('-created_at')[:10]
        results = []
        for message in messages:
            result = [message.text, naturaltime(message.created_at)]
            results.append(result)
        return JsonResponse(results, safe=False)


# References

# https://simpleisbetterthancomplex.com/tutorial/2016/07/27/how-to-return-json-encoded-response.html 
開發者ID:csev,項目名稱:dj4e-samples,代碼行數:14,代碼來源:views.py

示例10: get_last_successful_update

# 需要導入模塊: from django.contrib.humanize.templatetags import humanize [as 別名]
# 或者: from django.contrib.humanize.templatetags.humanize import naturaltime [as 別名]
def get_last_successful_update(obj):
    return naturaltime(obj.last_successful_update) 
開發者ID:SpisTresci,項目名稱:scrooge,代碼行數:4,代碼來源:admin.py

示例11: get_last_changing_offers_update

# 需要導入模塊: from django.contrib.humanize.templatetags import humanize [as 別名]
# 或者: from django.contrib.humanize.templatetags.humanize import naturaltime [as 別名]
def get_last_changing_offers_update(obj):
    return naturaltime(obj.last_changing_offers_update) 
開發者ID:SpisTresci,項目名稱:scrooge,代碼行數:4,代碼來源:admin.py

示例12: get_notifications

# 需要導入模塊: from django.contrib.humanize.templatetags import humanize [as 別名]
# 或者: from django.contrib.humanize.templatetags.humanize import naturaltime [as 別名]
def get_notifications(
        request,
        latest_id=None,
        is_viewed=False,
        max_results=10):
    """
    View that returns a JSON list of notifications for the current user as according
    to ``request.user``.

    :param: latest_id: The latest id of a notification. Use this to avoid
    retrieving the same notifications multiple times.
    :param: is_viewed: Set this to ``True`` if you also want to retrieve
    notifications that have already been viewed.

    :returns: An HTTPResponse object with JSON data::

        {'success': True,
         'total_count': total_count,
         'objects': [{'pk': n.pk,
                     'message': n.message,
                     'url': n.url,
                     'occurrences': n.occurrences,
                     'occurrences_msg': _('%d times') % n.occurrences,
                     'type': n.subscription.notification_type.key if n.subscription else None,
                     'since': naturaltime(n.created)} for n in notifications[:max_results]]}
    """

    notifications = models.Notification.objects.filter(
        Q(subscription__settings__user=request.user) | Q(user=request.user),
    )

    if is_viewed is not None:
        notifications = notifications.filter(is_viewed=is_viewed)

    total_count = notifications.count()

    if latest_id is not None:
        notifications = notifications.filter(id__gt=latest_id)

    notifications = notifications.order_by('-id')
    notifications = notifications.prefetch_related(
        'subscription',
        'subscription__notification_type')

    from django.contrib.humanize.templatetags.humanize import naturaltime

    return {'success': True,
            'total_count': total_count,
            'objects': [{'pk': n.pk,
                         'message': n.message,
                         'url': n.url,
                         'occurrences': n.occurrences,
                         'occurrences_msg': _('%d times') % n.occurrences,
                         'type': n.subscription.notification_type.key if n.subscription else None,
                         'since': naturaltime(n.created)} for n in notifications[:max_results]]} 
開發者ID:django-wiki,項目名稱:django-nyt,代碼行數:57,代碼來源:views.py

示例13: test_naturaltime_as_documented

# 需要導入模塊: from django.contrib.humanize.templatetags import humanize [as 別名]
# 或者: from django.contrib.humanize.templatetags.humanize import naturaltime [as 別名]
def test_naturaltime_as_documented(self):
        """
        #23340 -- Verify the documented behavior of humanize.naturaltime.
        """
        time_format = '%d %b %Y %H:%M:%S'
        documented_now = datetime.datetime.strptime('17 Feb 2007 16:30:00', time_format)

        test_data = (
            ('17 Feb 2007 16:30:00', 'now'),
            ('17 Feb 2007 16:29:31', '29 seconds ago'),
            ('17 Feb 2007 16:29:00', 'a minute ago'),
            ('17 Feb 2007 16:25:35', '4 minutes ago'),
            ('17 Feb 2007 15:30:29', '59 minutes ago'),
            ('17 Feb 2007 15:30:01', '59 minutes ago'),
            ('17 Feb 2007 15:30:00', 'an hour ago'),
            ('17 Feb 2007 13:31:29', '2 hours ago'),
            ('16 Feb 2007 13:31:29', '1 day, 2 hours ago'),
            ('16 Feb 2007 13:30:01', '1 day, 2 hours ago'),
            ('16 Feb 2007 13:30:00', '1 day, 3 hours ago'),
            ('17 Feb 2007 16:30:30', '30 seconds from now'),
            ('17 Feb 2007 16:30:29', '29 seconds from now'),
            ('17 Feb 2007 16:31:00', 'a minute from now'),
            ('17 Feb 2007 16:34:35', '4 minutes from now'),
            ('17 Feb 2007 17:30:29', 'an hour from now'),
            ('17 Feb 2007 18:31:29', '2 hours from now'),
            ('18 Feb 2007 16:31:29', '1 day from now'),
            ('26 Feb 2007 18:31:29', '1 week, 2 days from now'),
        )

        class DocumentedMockDateTime(datetime.datetime):
            @classmethod
            def now(cls, tz=None):
                if tz is None or tz.utcoffset(documented_now) is None:
                    return documented_now
                else:
                    return documented_now.replace(tzinfo=tz) + tz.utcoffset(now)

        orig_humanize_datetime = humanize.datetime
        humanize.datetime = DocumentedMockDateTime
        try:
            for test_time_string, expected_natural_time in test_data:
                test_time = datetime.datetime.strptime(test_time_string, time_format)
                natural_time = humanize.naturaltime(test_time).replace('\xa0', ' ')
                self.assertEqual(expected_natural_time, natural_time)
        finally:
            humanize.datetime = orig_humanize_datetime 
開發者ID:nesdis,項目名稱:djongo,代碼行數:48,代碼來源:tests.py

示例14: test_inflection_for_timedelta

# 需要導入模塊: from django.contrib.humanize.templatetags import humanize [as 別名]
# 或者: from django.contrib.humanize.templatetags.humanize import naturaltime [as 別名]
def test_inflection_for_timedelta(self):
        """
        Translation of '%d day'/'%d month'/… may differ depending on the context
        of the string it is inserted in.
        """
        test_list = [
            # "%(delta)s ago" translations
            now - datetime.timedelta(days=1),
            now - datetime.timedelta(days=2),
            now - datetime.timedelta(days=30),
            now - datetime.timedelta(days=60),
            now - datetime.timedelta(days=500),
            now - datetime.timedelta(days=865),
            # "%(delta)s from now" translations
            now + datetime.timedelta(days=1),
            now + datetime.timedelta(days=2),
            now + datetime.timedelta(days=30),
            now + datetime.timedelta(days=60),
            now + datetime.timedelta(days=500),
            now + datetime.timedelta(days=865),
        ]
        result_list = [
            'před 1\xa0dnem',
            'před 2\xa0dny',
            'před 1\xa0měsícem',
            'před 2\xa0měsíci',
            'před 1\xa0rokem, 4\xa0měsíci',
            'před 2\xa0lety, 4\xa0měsíci',
            'za 1\xa0den',
            'za 2\xa0dny',
            'za 1\xa0měsíc',
            'za 2\xa0měsíce',
            'za 1\xa0rok, 4\xa0měsíce',
            'za 2\xa0roky, 4\xa0měsíce',
        ]

        orig_humanize_datetime, humanize.datetime = humanize.datetime, MockDateTime
        try:
            # Choose a language with different naturaltime-past/naturaltime-future translations
            with translation.override('cs'), self.settings(USE_L10N=True):
                self.humanize_tester(test_list, result_list, 'naturaltime')
        finally:
            humanize.datetime = orig_humanize_datetime 
開發者ID:nesdis,項目名稱:djongo,代碼行數:45,代碼來源:tests.py


注:本文中的django.contrib.humanize.templatetags.humanize.naturaltime方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。