我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.template.defaultfilters.date()。
def get(self, request, *args, **kwargs): _page = get_object_or_404(Page, pk=request.GET.get('page_id')) # release page for all users which did not update during the last timeframe PageIndicator.objects.filter(edited_on__lte=self.time_past, page=_page).delete() page_indicators = PageIndicator.objects.filter(edited_on__gte=self.time_past, page=_page)\ .exclude(editor=request.user) response = {} if page_indicators.exists(): response['conflict'] = True editing_user = page_indicators.first() response['concurrent_user'] = [editing_user.editor.username] # default behavior for concurrent users is blocking response['block_editing'] = getattr(settings, 'CONCURRENT_BLOCK_EDITING', BLOCK_EDITING_DEFAULT) response['message'] = _(u'Unfortunately you cannot edit this page at the moment: ' u'user {user} is blocking it since {time}').format( user=editing_user.editor, time=_date(editing_user.started_editing, 'D, d. b, H:i')) else: response['conflict'] = False return JsonResponse(json.dumps(response), safe=False)
def html_date(value, displayfmt=None, datetimefmt='c', **kwargs): """Format a date and wrap it in a html <time> element. Additional html attributes may be provided as kwargs (e.g. 'class'). Note: Converts the value to localtime as we loose the expects_localtime flag functionality by directly calling the date filter from django. """ localtime_value = timezone.localtime(value) displaydate = defaultfilters.date(localtime_value, displayfmt) datetime = defaultfilters.date(localtime_value, datetimefmt) attribs = flatatt(kwargs) result = '<time %s datetime="%s">%s</time>' % (attribs, datetime, displaydate) return mark_safe(result)
def format_date(date): """Format date string.""" return defaultfilters.date(date, "j b Y")
def naturalday(value, arg=None): """ For date values that are tomorrow, today or yesterday compared to present day returns representing string. Otherwise, returns a string formatted according to settings.DATE_FORMAT. """ try: tzinfo = getattr(value, 'tzinfo', None) value = date(value.year, value.month, value.day) except AttributeError: # Passed value wasn't a date object return value except ValueError: # Date arguments out of range return value today = datetime.now(tzinfo).date() delta = value - today if delta.days == 0: return _('today') elif delta.days == 1: return _('tomorrow') elif delta.days == -1: return _('yesterday') return defaultfilters.date(value, arg) # This filter doesn't require expects_localtime=True because it deals properly # with both naive and aware datetimes. Therefore avoid the cost of conversion.
def generate_attachment_filename(instance, filename): filename, ext = os.path.splitext(filename) if ext not in ('.jpg', '.jpeg', '.png', '.bmp', '.gif', '.rar', '.gz', '.zip', '.7z', '.txt', '.pdf', '.doc', '.docx', '.ppt', '.pptx', ): ext = '.attach' filename = "%s-%s%s" % (uuid4(), get_random_string(length=8), ext) tzinfo = timezone.get_current_timezone() if settings.USE_TZ else None date_dir = date(datetime.now(tz=tzinfo), 'Y/m') return "attachment/%s/%s" % (date_dir, filename)
def generate_image_filename(instance, filename): filename, ext = os.path.splitext(filename) filename = "%s-%s%s" % (uuid4(), get_random_string(length=8), ext) tzinfo = timezone.get_current_timezone() if settings.USE_TZ else None date_dir = date(datetime.now(tz=tzinfo), 'Y/m/d') return "images/%s/%s" % (date_dir, filename)
def __unicode__(self): return _date(self.day, "Y-m-d (D)")
def __str__(self): return ugettext('%(title)s: %(start)s - %(end)s') % { 'title': self.title, 'start': date(self.start, django_settings.DATE_FORMAT), 'end': date(self.end, django_settings.DATE_FORMAT), }
def get_occurrence(self, date): if timezone.is_naive(date) and django_settings.USE_TZ: date = timezone.make_aware(date, timezone.utc) rule = self.get_rrule_object() if rule: next_occurrence = rule.after(date, inc=True) else: next_occurrence = self.start if next_occurrence == date: try: return Occurrence.objects.get(event=self, original_start=date) except Occurrence.DoesNotExist: return self._create_occurrence(next_occurrence)
def __str__(self): return ugettext("%(start)s to %(end)s") % { 'start': date(self.start, django_settings.DATE_FORMAT), 'end': date(self.end, django_settings.DATE_FORMAT) }
def __str__(self): date_format = 'l, %s' % settings.DATE_FORMAT return ugettext('Week: %(start)s-%(end)s') % { 'start': date_filter(self.start, date_format), 'end': date_filter(self.end, date_format), }
def __str__(self): date_format = 'l, %s' % settings.DATE_FORMAT return ugettext('Day: %(start)s-%(end)s') % { 'start': date_filter(self.start, date_format), 'end': date_filter(self.end, date_format), }
def format_data_movimento(self): return '%s' % date(self.data_movimento, "d/m/Y")
def format_data_emissao(self): return '%s' % date(self.data_emissao, "d/m/Y")
def format_data_vencimento(self): return '%s' % date(self.data_vencimento, "d/m/Y")
def format_data_entrega(self): return '%s' % date(self.data_entrega, "d/m/Y")
def format_data_emissao(self): return '%s' % date(self.dhemi.date(), "d/m/Y")
def format_data_pagamento(self): return '%s' % date(self.data_pagamento, "d/m/Y")
def default_datetime(value): """Returns the date as represented by the default datetime format""" try: v = date(value, DATETIME_FORMAT) except: return value return v
def __str__(self): return _date(self.day, "Y-m-d (D)")
def test_naturalday(self): today = datetime.date.today() yesterday = today - datetime.timedelta(days=1) tomorrow = today + datetime.timedelta(days=1) someday = today - datetime.timedelta(days=10) notdate = "I'm not a date value" test_list = (today, yesterday, tomorrow, someday, notdate, None) someday_result = defaultfilters.date(someday) result_list = (_('today'), _('yesterday'), _('tomorrow'), someday_result, "I'm not a date value", None) self.humanize_tester(test_list, result_list, 'naturalday')
def test_naturalday_tz(self): today = datetime.date.today() tz_one = tzinfo.FixedOffset(datetime.timedelta(hours=-12)) tz_two = tzinfo.FixedOffset(datetime.timedelta(hours=12)) # Can be today or yesterday date_one = datetime.datetime(today.year, today.month, today.day, tzinfo=tz_one) naturalday_one = humanize.naturalday(date_one) # Can be today or tomorrow date_two = datetime.datetime(today.year, today.month, today.day, tzinfo=tz_two) naturalday_two = humanize.naturalday(date_two) # As 24h of difference they will never be the same self.assertNotEqual(naturalday_one, naturalday_two)
def present_dt(dt): return '%s at %s' % ( defaultfilters.date(dt, 'Y-m-d'), defaultfilters.time(dt, 'f A e'))
def timesince(value, now=None): from django.template.defaultfilters import timesince if now is None: now = timezone.now() if not value: return _('never') if value < (now - timedelta(days=5)): return value.date() value = (' '.join(timesince(value, now).split(' ')[0:2])).strip(',') if value == _('0 minutes'): return _('just now') if value == _('1 day'): return _('yesterday') return value + _(' ago')