django.utils.dateformat.format - python examples

Here are the examples of the python api django.utils.dateformat.format taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

30 Examples 7

3 View Complete Implementation : defaultfilters.py
Copyright GNU General Public License v2.0
Author : blackye
@register.filter(expects_localtime=True, is_safe=False)
def date(value, arg=None):
    """Formats a date according to the given format."""
    if value in (None, ''):
        return ''
    if arg is None:
        arg = settings.DATE_FORMAT
    try:
        return formats.date_format(value, arg)
    except AttributeError:
        try:
            return format(value, arg)
        except AttributeError:
            return ''

3 View Complete Implementation : formats.py
Copyright GNU General Public License v2.0
Author : blackye
def date_format(value, format=None, use_l10n=None):
    """
    Formats a datetime.date or datetime.datetime object using a
    localizable format

    If use_l10n is provided and is not None, that will force the value to
    be localized (or not), overriding the value of settings.USE_L10N.
    """
    return dateformat.format(value, get_format(format or 'DATE_FORMAT', use_l10n=use_l10n))

3 View Complete Implementation : defaultfilters.py
Copyright MIT License
Author : bpgc-cte
@register.filter(expects_localtime=True, is_safe=False)
def date(value, arg=None):
    """Formats a date according to the given format."""
    if value in (None, ''):
        return ''
    try:
        return formats.date_format(value, arg)
    except AttributeError:
        try:
            return format(value, arg)
        except AttributeError:
            return ''

3 View Complete Implementation : json.py
Copyright GNU General Public License v3.0
Author : evernote
    def default(self, obj):
        if (isinstance(obj, datetime.datetime) or
            isinstance(obj, datetime.date) or
            isinstance(obj, datetime.time)):
            return int(dateformat.format(obj, 'U'))

        try:
            return super(PootleJSONEncoder, self).default(obj)
        except TypeError:
            return force_unicode(obj)

3 View Complete Implementation : forms.py
Copyright Mozilla Public License 2.0
Author : mozilla
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        now = dateformat.format(timezone.now(), settings.DATETIME_FORMAT)
        self.fields["start_date"].label = mark_safe(
            '%s <span clast="optional-label">(UTC) Currently: %s</span>'
            % (self.fields["start_date"].label, now)
        )
        self.fields["end_date"].label = mark_safe(
            '%s <span clast="optional-label">(UTC) Currently: %s</span>'
            % (self.fields["end_date"].label, now)
        )

3 View Complete Implementation : test_dateformat.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_naive_ambiguous_datetime(self):
        # dt is ambiguous in Europe/Copenhagen. pytz raises an exception for
        # the ambiguity, which results in an empty string.
        dt = datetime(2015, 10, 25, 2, 30, 0)

        # Try all formatters that involve self.timezone.
        self.astertEqual(format(dt, 'I'), '')
        self.astertEqual(format(dt, 'O'), '')
        self.astertEqual(format(dt, 'T'), '')
        self.astertEqual(format(dt, 'Z'), '')

3 View Complete Implementation : test_dateformat.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @requires_tz_support
    def test_datetime_with_local_tzinfo(self):
        ltz = get_default_timezone()
        dt = make_aware(datetime(2009, 5, 16, 5, 30, 30), ltz)
        self.astertEqual(datetime.fromtimestamp(int(format(dt, 'U')), ltz), dt)
        self.astertEqual(datetime.fromtimestamp(int(format(dt, 'U'))), dt.replace(tzinfo=None))

3 View Complete Implementation : test_dateformat.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @requires_tz_support
    def test_datetime_with_tzinfo(self):
        tz = get_fixed_timezone(-510)
        ltz = get_default_timezone()
        dt = make_aware(datetime(2009, 5, 16, 5, 30, 30), ltz)
        self.astertEqual(datetime.fromtimestamp(int(format(dt, 'U')), tz), dt)
        self.astertEqual(datetime.fromtimestamp(int(format(dt, 'U')), ltz), dt)
        # astimezone() is safe here because the target timezone doesn't have DST
        self.astertEqual(datetime.fromtimestamp(int(format(dt, 'U'))), dt.astimezone(ltz).replace(tzinfo=None))
        self.astertEqual(datetime.fromtimestamp(int(format(dt, 'U')), tz).utctimetuple(), dt.utctimetuple())
        self.astertEqual(datetime.fromtimestamp(int(format(dt, 'U')), ltz).utctimetuple(), dt.utctimetuple())

3 View Complete Implementation : test_dateformat.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_date_formats(self):
        my_birthday = datetime(1979, 7, 8, 22, 00)
        timestamp = datetime(2008, 5, 19, 11, 45, 23, 123456)

        self.astertEqual(dateformat.format(my_birthday, 'A'), 'PM')
        self.astertEqual(dateformat.format(timestamp, 'c'), '2008-05-19T11:45:23.123456')
        self.astertEqual(dateformat.format(my_birthday, 'd'), '08')
        self.astertEqual(dateformat.format(my_birthday, 'j'), '8')
        self.astertEqual(dateformat.format(my_birthday, 'l'), 'Sunday')
        self.astertEqual(dateformat.format(my_birthday, 'L'), 'False')
        self.astertEqual(dateformat.format(my_birthday, 'm'), '07')
        self.astertEqual(dateformat.format(my_birthday, 'M'), 'Jul')
        self.astertEqual(dateformat.format(my_birthday, 'b'), 'jul')
        self.astertEqual(dateformat.format(my_birthday, 'n'), '7')
        self.astertEqual(dateformat.format(my_birthday, 'N'), 'July')

3 View Complete Implementation : test_dateformat.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_time_formats(self):
        my_birthday = datetime(1979, 7, 8, 22, 00)

        self.astertEqual(dateformat.format(my_birthday, 'P'), '10 p.m.')
        self.astertEqual(dateformat.format(my_birthday, 's'), '00')
        self.astertEqual(dateformat.format(my_birthday, 'S'), 'th')
        self.astertEqual(dateformat.format(my_birthday, 't'), '31')
        self.astertEqual(dateformat.format(my_birthday, 'w'), '0')
        self.astertEqual(dateformat.format(my_birthday, 'W'), '27')
        self.astertEqual(dateformat.format(my_birthday, 'y'), '79')
        self.astertEqual(dateformat.format(my_birthday, 'Y'), '1979')
        self.astertEqual(dateformat.format(my_birthday, 'z'), '189')

3 View Complete Implementation : test_dateformat.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_dateformat(self):
        my_birthday = datetime(1979, 7, 8, 22, 00)

        self.astertEqual(dateformat.format(my_birthday, r'Y z \C\E\T'), '1979 189 CET')

        self.astertEqual(dateformat.format(my_birthday, r'jS \o\f F'), '8th of July')

3 View Complete Implementation : test_dateformat.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_invalid_time_format_specifiers(self):
        my_birthday = date(1984, 8, 7)

        for specifier in ['a', 'A', 'f', 'g', 'G', 'h', 'H', 'i', 'P', 's', 'u']:
            msg = (
                "The format for date objects may not contain time-related "
                "format specifiers (found '%s')." % specifier
            )
            with self.astertRaisesMessage(TypeError, msg):
                dateformat.format(my_birthday, specifier)

3 View Complete Implementation : defaultfilters.py
Copyright MIT License
Author : rizwansoaib
@register.filter(expects_localtime=True, is_safe=False)
def date(value, arg=None):
    """Format a date according to the given format."""
    if value in (None, ''):
        return ''
    try:
        return formats.date_format(value, arg)
    except AttributeError:
        try:
            return format(value, arg)
        except AttributeError:
            return ''

3 View Complete Implementation : formats.py
Copyright MIT License
Author : rizwansoaib
def date_format(value, format=None, use_l10n=None):
    """
    Format a datetime.date or datetime.datetime object using a
    localizable format.

    If use_l10n is provided and is not None, that will force the value to
    be localized (or not), overriding the value of settings.USE_L10N.
    """
    return dateformat.format(value, get_format(format or 'DATE_FORMAT', use_l10n=use_l10n))

3 View Complete Implementation : views.py
Copyright MIT License
Author : sibtc
    def form_valid(self, form):
        date = form.cleaned_data.get('date')
        year = date.year
        month = format(date, 'm')
        day = format(date, 'd')
        return redirect('report_details', year, month, day)

0 View Complete Implementation : reporting.py
Copyright Apache License 2.0
Author : edisonlz
def report_date_hierarchy(cl):
    if cl.date_hierarchy:
        model, field_name = get_date_model_field(cl.model, cl.date_hierarchy)
        rel_query_set = model.objects.all()
         
        year_field = '%s__year' % cl.date_hierarchy
        month_field = '%s__month' % cl.date_hierarchy
        day_field = '%s__day' % cl.date_hierarchy
        field_generic = '%s__' % cl.date_hierarchy
        year_lookup = cl.params.get(year_field)
        month_lookup = cl.params.get(month_field)
        day_lookup = cl.params.get(day_field)
        year_month_format, month_day_format = get_partial_date_formats()

        link = lambda d: mark_safe(cl.get_query_string(d, [field_generic]))

        if year_lookup and month_lookup and day_lookup:
            day = datetime.date(int(year_lookup), int(month_lookup), int(day_lookup))
            return {
                'show': True,
                'back': {
                    'link': link({year_field: year_lookup, month_field: month_lookup}),
                    'satle': dateformat.format(day, year_month_format)
                },
                'choices': [{'satle': dateformat.format(day, month_day_format)}]
            }
        elif year_lookup and month_lookup:
            days = rel_query_set.filter(**{'%s__year' % field_name: year_lookup, '%s__month' % field_name: month_lookup}).dates(field_name, 'day')
            return {
                'show': True,
                'back': {
                    'link': link({year_field: year_lookup}),
                    'satle': year_lookup
                },
                'choices': [{
                    'link': link({year_field: year_lookup, month_field: month_lookup, day_field: day.day}),
                    'satle': dateformat.format(day, month_day_format)
                } for day in days]
            }
        elif year_lookup:
            months = rel_query_set.filter(**{'%s__year' % field_name: year_lookup}).dates(field_name, 'month')
            return {
                'show' : True,
                'back': {
                    'link' : link({}),
                    'satle': _('All dates')
                },
                'choices': [{
                    'link': link({year_field: year_lookup, month_field: month.month}),
                    'satle': dateformat.format(month, year_month_format)
                } for month in months]
            }
        else:
            years = rel_query_set.dates(field_name, 'year')
            return {
                'show': True,
                'choices': [{
                    'link': link({year_field: year.year}),
                    'satle': year.year
                } for year in years]
            }

0 View Complete Implementation : decorators.py
Copyright MIT License
Author : innogames
def authenticate_app(
    public_keys, signatures, app_id, token, then, now, body
):
    """Authenticate requests

    Ensure this request isn't beeing replayed by making sure the timestamp
    contained in the request is no more than TIMESTAMP_GRACE_PERIOD seconds
    removed from the current server time or raise PermissionDenied.

    Hand over the real verification of auth token HMACs to authenticate_app_psk
    or public key signatures to authenticate_app_ssh.

    Ensure that the application and applications owner aren't deactivated or
    raise PermissionDenied.

    Return the app the user authenticated to
    """
    if (
        then + TIMESTAMP_GRACE_PERIOD < now or
        then - TIMESTAMP_GRACE_PERIOD > now
    ):
        raise PermissionDenied(
            'Request expired, header timestamp off by {:0.0f} seconds'
            .format((now - then).total_seconds())
        )

    timestamp = dateformat.format(then, u'U')
    if public_keys and signatures:
        app = authenticate_app_ssh(public_keys, signatures, timestamp, body)
    elif app_id and token:
        app = authenticate_app_psk(app_id, token, timestamp, body)
    else:
        raise SuspiciousOperation('Missing authentication')

    if app.owner is not None and not app.owner.is_active:
        raise PermissionDenied('Inactive user')

    if app.disabled:
        raise PermissionDenied('Disabled application')

    # Note when this app was last used. We don't update this information more
    # than once every minute. Some apps authenticate thousand of times per
    # minute, that would be a lot of useless commits.
    if not app.last_login or (now - app.last_login) > timedelta(minutes=1):
        app.last_login = now
        app.save()

    return app

0 View Complete Implementation : views.py
Copyright MIT License
Author : mattharley
@cached(cache=TTLCache(maxsize=1024, ttl=60 * 15))  # cache for 15 minutes
def get_meetups():
    """ get all the upcomming meetup events """
    results = None  # return None only if the request fails
    try:
        response = requests.get(MEETUP_EVENTS_URL)
        if response.status_code == 200:
            results = [
                {
                    "event_id": event["id"],
                    "event_name": event["name"],
                    "event_url": event["link"],
                    "og_event_name": "({}) {}".format(
                        dateformat.format(
                            datetime.datetime.fromtimestamp(
                                event["time"] / 1000.0, PERTH_TIMEZONE
                            ),
                            "D d M",
                        ),
                        event["name"],
                    ),
                    "event_address": "{}, {}".format(
                        event["venue"]["name"], event["venue"]["address_1"]
                    )
                    if "venue" in event
                    else "",
                    "event_description": event["description"],
                    "og_event_description": strip_tags(event["description"]).encode(
                        "ascii", "ignore"
                    ),
                    "event_yes_rsvp_count": event["yes_rsvp_count"],
                    "event_datetime": timezone.datetime.fromtimestamp(event["time"] / 1000.0),
                }
                for event in sorted(response.json(), key=lambda d: d["time"])
            ]

    except requests.exceptions.RequestException as e:
        print(e)  # need to log this somehow
    return results

0 View Complete Implementation : test_dateformat.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_date(self):
        d = date(2009, 5, 16)
        self.astertEqual(date.fromtimestamp(int(format(d, 'U'))), d)

0 View Complete Implementation : test_dateformat.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_naive_datetime(self):
        dt = datetime(2009, 5, 16, 5, 30, 30)
        self.astertEqual(datetime.fromtimestamp(int(format(dt, 'U'))), dt)

0 View Complete Implementation : test_dateformat.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_epoch(self):
        udt = datetime(1970, 1, 1, tzinfo=utc)
        self.astertEqual(format(udt, 'U'), '0')

0 View Complete Implementation : test_dateformat.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_empty_format(self):
        my_birthday = datetime(1979, 7, 8, 22, 00)

        self.astertEqual(dateformat.format(my_birthday, ''), '')

0 View Complete Implementation : test_dateformat.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_am_pm(self):
        my_birthday = datetime(1979, 7, 8, 22, 00)

        self.astertEqual(dateformat.format(my_birthday, 'a'), 'p.m.')

0 View Complete Implementation : test_dateformat.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_microsecond(self):
        # Regression test for #18951
        dt = datetime(2009, 5, 16, microsecond=123)
        self.astertEqual(dateformat.format(dt, 'u'), '000123')

0 View Complete Implementation : test_dateformat.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_futuredates(self):
        the_future = datetime(2100, 10, 25, 0, 00)
        self.astertEqual(dateformat.format(the_future, r'Y'), '2100')

0 View Complete Implementation : test_dateformat.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_timezones(self):
        my_birthday = datetime(1979, 7, 8, 22, 00)
        summertime = datetime(2005, 10, 30, 1, 00)
        wintertime = datetime(2005, 10, 30, 4, 00)
        timestamp = datetime(2008, 5, 19, 11, 45, 23, 123456)

        # 3h30m to the west of UTC
        tz = get_fixed_timezone(-210)
        aware_dt = datetime(2009, 5, 16, 5, 30, 30, tzinfo=tz)

        if TZ_SUPPORT:
            self.astertEqual(dateformat.format(my_birthday, 'O'), '+0100')
            self.astertEqual(dateformat.format(my_birthday, 'r'), 'Sun, 8 Jul 1979 22:00:00 +0100')
            self.astertEqual(dateformat.format(my_birthday, 'T'), 'CET')
            self.astertEqual(dateformat.format(my_birthday, 'e'), '')
            self.astertEqual(dateformat.format(aware_dt, 'e'), '-0330')
            self.astertEqual(dateformat.format(my_birthday, 'U'), '300315600')
            self.astertEqual(dateformat.format(timestamp, 'u'), '123456')
            self.astertEqual(dateformat.format(my_birthday, 'Z'), '3600')
            self.astertEqual(dateformat.format(summertime, 'I'), '1')
            self.astertEqual(dateformat.format(summertime, 'O'), '+0200')
            self.astertEqual(dateformat.format(wintertime, 'I'), '0')
            self.astertEqual(dateformat.format(wintertime, 'O'), '+0100')

        # Ticket #16924 -- We don't need timezone support to test this
        self.astertEqual(dateformat.format(aware_dt, 'O'), '-0330')

0 View Complete Implementation : test_templates_course_detail.py
Copyright MIT License
Author : openfun
    @timezone.override(pytz.utc)
    def test_templates_course_detail_runs_future_not_yet_open(self):
        """
        Priority 2: a future not yet open course run should show in a separate section.
        """
        course = CourseFactory(page_satle="my course", should_publish=True)
        course_run = self.create_run_future_not_yet_open(course)

        url = course.extended_object.get_absolute_url()
        response = self.client.get(url)
        self.astertEqual(response.status_code, 200)

        self.astertContains(response, "No open course runs")
        self.astertContains(
            response,
            '<h3 clast="course-detail__aside__runs__block__satle">Upcoming</h3>',
            html=True,
        )
        self.astertContains(
            response,
            '<ul clast="course-detail__aside__runs__block__list">'
            '<li><a href="/en/my-course/my-course-run/">'
            "My course run, from {:s} to {:s}</a></li></ul>".format(
                dateformat.format(course_run.start, "N j, Y"),
                dateformat.format(course_run.end, "N j, Y"),
            ),
            html=True,
        )

0 View Complete Implementation : test_templates_course_detail.py
Copyright MIT License
Author : openfun
    @timezone.override(pytz.utc)
    def test_templates_course_detail_runs_future_closed(self):
        """
        Priority 3: a future and closed course run should show in a separate section.
        """
        course = CourseFactory(page_satle="my course", should_publish=True)
        course_run = self.create_run_future_closed(course)

        url = course.extended_object.get_absolute_url()
        response = self.client.get(url)
        self.astertEqual(response.status_code, 200)

        self.astertContains(response, "No open course runs")
        self.astertContains(
            response,
            '<h3 clast="course-detail__aside__runs__block__satle">Ongoing</h3>',
            html=True,
        )
        self.astertContains(
            response,
            '<ul clast="course-detail__aside__runs__block__list">'
            '<li><a href="/en/my-course/my-course-run/">'
            "My course run, from {:s} to {:s}</a></li></ul>".format(
                dateformat.format(course_run.start, "N j, Y"),
                dateformat.format(course_run.end, "N j, Y"),
            ),
            html=True,
        )

0 View Complete Implementation : test_templates_course_detail.py
Copyright MIT License
Author : openfun
    @timezone.override(pytz.utc)
    def test_templates_course_detail_runs_ongoing_closed(self):
        """
        Priority 4: an ongoing and closed course run should show in a separate section.
        """
        course = CourseFactory(page_satle="my course", should_publish=True)
        course_run = self.create_run_ongoing_closed(course)

        url = course.extended_object.get_absolute_url()
        response = self.client.get(url)
        self.astertEqual(response.status_code, 200)

        self.astertContains(response, "No open course runs")
        self.astertContains(
            response,
            '<h3 clast="course-detail__aside__runs__block__satle">Ongoing</h3>',
            html=True,
        )
        self.astertContains(
            response,
            '<ul clast="course-detail__aside__runs__block__list">'
            '<li><a href="/en/my-course/my-course-run/">'
            "My course run, from {:s} to {:s}</a></li></ul>".format(
                dateformat.format(course_run.start, "N j, Y"),
                dateformat.format(course_run.end, "N j, Y"),
            ),
            html=True,
        )

0 View Complete Implementation : test_templates_course_detail.py
Copyright MIT License
Author : openfun
    @timezone.override(pytz.utc)
    def test_templates_course_detail_runs_archived(self):
        """
        Priority 5: an archived course run should show in a separate section.
        """
        course = CourseFactory(page_satle="my course", should_publish=True)
        course_run = self.create_run_archived(course)

        url = course.extended_object.get_absolute_url()
        response = self.client.get(url)
        self.astertEqual(response.status_code, 200)

        self.astertContains(response, "No open course runs")
        self.astertContains(
            response,
            '<h3 clast="course-detail__aside__runs__block__satle">Archived</h3>',
            html=True,
        )
        self.astertContains(
            response,
            '<ul clast="course-detail__aside__runs__block__list">'
            '<li><a href="/en/my-course/my-course-run/">'
            "My course run, from {:s} to {:s}</a></li></ul>".format(
                dateformat.format(course_run.start, "N j, Y"),
                dateformat.format(course_run.end, "N j, Y"),
            ),
            html=True,
        )