Python django.contrib.humanize.templatetags.humanize.naturaltime() Examples
The following are 20
code examples of django.contrib.humanize.templatetags.humanize.naturaltime().
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.contrib.humanize.templatetags.humanize
, or try the search function
.
Example #1
Source File: servo_tags.py From Servo with BSD 2-Clause "Simplified" License | 7 votes |
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)
Example #2
Source File: serializers.py From elmer with MIT License | 5 votes |
def get_data_naturaltime(self, obj): """ Returns human readable time. :return: string """ return naturaltime(obj.date)
Example #3
Source File: admin.py From scrooge with MIT License | 5 votes |
def get_last_changing_offers_update(obj): return naturaltime(obj.last_changing_offers_update)
Example #4
Source File: admin.py From scrooge with MIT License | 5 votes |
def get_last_successful_update(obj): return naturaltime(obj.last_successful_update)
Example #5
Source File: views.py From dj4e-samples with MIT License | 5 votes |
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
Example #6
Source File: views.py From dj4e-samples with MIT License | 5 votes |
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
Example #7
Source File: serializers.py From appstore with GNU Affero General Public License v3.0 | 5 votes |
def get_relative_rated_at(self, obj): return naturaltime(obj.rated_at)
Example #8
Source File: utils.py From API-Manager with GNU Affero General Public License v3.0 | 5 votes |
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')
Example #9
Source File: serializers.py From elmer with MIT License | 5 votes |
def get_created_naturaltime(self, obj): """Returns human readable time.""" return naturaltime(obj.created)
Example #10
Source File: serializers.py From elmer with MIT License | 5 votes |
def get_created_naturaltime(self, obj): """Returns human readable time.""" return naturaltime(obj.created)
Example #11
Source File: serializers.py From elmer with MIT License | 5 votes |
def get_created_naturaltime(self, obj): """Returns human readable time.""" return naturaltime(obj.created)
Example #12
Source File: serializers.py From elmer with MIT License | 5 votes |
def get_created_naturaltime(self, obj): """Returns human readable time.""" return naturaltime(obj.created)
Example #13
Source File: TimeUtils.py From civet with Apache License 2.0 | 5 votes |
def human_time_str(d): #return d.strftime('%H:%M:%S %m/%d/%y') return naturaltime(d)
Example #14
Source File: TimeUtils.py From civet with Apache License 2.0 | 5 votes |
def display_time_str(d): #return d.strftime('%H:%M:%S %m/%d/%y') return naturaltime(d)
Example #15
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 4 votes |
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
Example #16
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 4 votes |
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
Example #17
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 4 votes |
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
Example #18
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 4 votes |
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
Example #19
Source File: views.py From django-nyt with Apache License 2.0 | 4 votes |
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]]}
Example #20
Source File: views.py From django-nyt with Apache License 2.0 | 4 votes |
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]]}