Lightly refactored django.utils.dateformat to make it use less code. Also integrated some of Sune's improvements from the #479 patch, including support for backslash escaping. Also vastly improved template docs for the {% now %} tag

git-svn-id: http://code.djangoproject.com/svn/django/trunk@969 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Adrian Holovaty 2005-10-20 05:30:11 +00:00
parent 539e53ccf1
commit 4c327b9c86
2 changed files with 171 additions and 181 deletions

View File

@ -11,64 +11,62 @@ Usage:
>>> >>>
""" """
from django.utils.dates import MONTHS, MONTHS_AP, WEEKDAYS
from calendar import isleap from calendar import isleap
from dates import MONTHS, MONTHS_AP, WEEKDAYS import re
class DateFormat: re_formatchars = re.compile(r'(?<!\\)([aABdDfFgGhHiIjlLmMnNOPrsStTUwWyYzZ])')
year_days = [None, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334] re_escaped = re.compile(r'\\(.)')
def __init__(self, d): class Formatter:
self.date = d def format(self, formatstr):
pieces = []
for i, piece in enumerate(re_formatchars.split(formatstr)):
if i % 2:
pieces.append(str(getattr(self, piece)()))
elif piece:
pieces.append(re_escaped.sub(r'\1', piece))
return ''.join(pieces)
class TimeFormat(Formatter):
def __init__(self, t):
self.data = t
def a(self): def a(self):
"'a.m.' or 'p.m.'" "'a.m.' or 'p.m.'"
if self.date.hour > 11: if self.data.hour > 11:
return 'p.m.' return 'p.m.'
return 'a.m.' return 'a.m.'
def A(self): def A(self):
"'AM' or 'PM'" "'AM' or 'PM'"
if self.date.hour > 11: return self.a().upper()
return 'PM'
return 'AM'
def B(self): def B(self):
"Swatch Internet time" "Swatch Internet time"
raise NotImplementedError raise NotImplementedError
def d(self):
"Day of the month, 2 digits with leading zeros; i.e. '01' to '31'"
return '%02d' % self.date.day
def D(self):
"Day of the week, textual, 3 letters; e.g. 'Fri'"
return WEEKDAYS[self.date.weekday()][0:3]
def f(self): def f(self):
""" """
Time, in 12-hour hours and minutes, with minutes left off if they're zero. Time, in 12-hour hours and minutes, with minutes left off if they're zero.
Examples: '1', '1:30', '2:05', '2' Examples: '1', '1:30', '2:05', '2'
Proprietary extension. Proprietary extension.
""" """
if self.date.minute == 0: if self.data.minute == 0:
return self.g() return self.g()
return '%s:%s' % (self.g(), self.i()) return '%s:%s' % (self.g(), self.i())
def F(self):
"Month, textual, long; e.g. 'January'"
return MONTHS[self.date.month]
def g(self): def g(self):
"Hour, 12-hour format without leading zeros; i.e. '1' to '12'" "Hour, 12-hour format without leading zeros; i.e. '1' to '12'"
if self.date.hour == 0: if self.data.hour == 0:
return 12 return 12
if self.date.hour > 12: if self.data.hour > 12:
return self.date.hour - 12 return self.data.hour - 12
return self.date.hour return self.data.hour
def G(self): def G(self):
"Hour, 24-hour format without leading zeros; i.e. '0' to '23'" "Hour, 24-hour format without leading zeros; i.e. '0' to '23'"
return self.date.hour return self.data.hour
def h(self): def h(self):
"Hour, 12-hour format; i.e. '01' to '12'" "Hour, 12-hour format; i.e. '01' to '12'"
@ -80,43 +78,7 @@ class DateFormat:
def i(self): def i(self):
"Minutes; i.e. '00' to '59'" "Minutes; i.e. '00' to '59'"
return '%02d' % self.date.minute return '%02d' % self.data.minute
def I(self):
"'1' if Daylight Savings Time, '0' otherwise."
raise NotImplementedError
def j(self):
"Day of the month without leading zeros; i.e. '1' to '31'"
return self.date.day
def l(self):
"Day of the week, textual, long; e.g. 'Friday'"
return WEEKDAYS[self.date.weekday()]
def L(self):
"Boolean for whether it is a leap year; i.e. True or False"
return isleap(self.date.year)
def m(self):
"Month; i.e. '01' to '12'"
return '%02d' % self.date.month
def M(self):
"Month, textual, 3 letters; e.g. 'Jan'"
return MONTHS[self.date.month][0:3]
def n(self):
"Month without leading zeros; i.e. '1' to '12'"
return self.date.month
def N(self):
"Month abbreviation in Associated Press style. Proprietary extension."
return MONTHS_AP[self.date.month]
def O(self):
"Difference to Greenwich time in hours; e.g. '+0200'"
raise NotImplementedError
def P(self): def P(self):
""" """
@ -125,25 +87,79 @@ class DateFormat:
Examples: '1 a.m.', '1:30 p.m.', 'midnight', 'noon', '12:30 p.m.' Examples: '1 a.m.', '1:30 p.m.', 'midnight', 'noon', '12:30 p.m.'
Proprietary extension. Proprietary extension.
""" """
if self.date.minute == 0 and self.date.hour == 0: if self.data.minute == 0 and self.data.hour == 0:
return 'midnight' return 'midnight'
if self.date.minute == 0 and self.date.hour == 12: if self.data.minute == 0 and self.data.hour == 12:
return 'noon' return 'noon'
return '%s %s' % (self.f(), self.a()) return '%s %s' % (self.f(), self.a())
def s(self):
"Seconds; i.e. '00' to '59'"
return '%02d' % self.data.second
class DateFormat(Formatter):
year_days = [None, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
def __init__(self, d):
self.data = d
def d(self):
"Day of the month, 2 digits with leading zeros; i.e. '01' to '31'"
return '%02d' % self.data.day
def D(self):
"Day of the week, textual, 3 letters; e.g. 'Fri'"
return WEEKDAYS[self.data.weekday()][0:3]
def F(self):
"Month, textual, long; e.g. 'January'"
return MONTHS[self.data.month]
def I(self):
"'1' if Daylight Savings Time, '0' otherwise."
raise NotImplementedError
def j(self):
"Day of the month without leading zeros; i.e. '1' to '31'"
return self.data.day
def l(self):
"Day of the week, textual, long; e.g. 'Friday'"
return WEEKDAYS[self.data.weekday()]
def L(self):
"Boolean for whether it is a leap year; i.e. True or False"
return isleap(self.data.year)
def m(self):
"Month; i.e. '01' to '12'"
return '%02d' % self.data.month
def M(self):
"Month, textual, 3 letters; e.g. 'Jan'"
return MONTHS[self.data.month][0:3]
def n(self):
"Month without leading zeros; i.e. '1' to '12'"
return self.data.month
def N(self):
"Month abbreviation in Associated Press style. Proprietary extension."
return MONTHS_AP[self.data.month]
def O(self):
"Difference to Greenwich time in hours; e.g. '+0200'"
raise NotImplementedError
def r(self): def r(self):
"RFC 822 formatted date; e.g. 'Thu, 21 Dec 2000 16:01:07 +0200'" "RFC 822 formatted date; e.g. 'Thu, 21 Dec 2000 16:01:07 +0200'"
raise NotImplementedError raise NotImplementedError
def s(self):
"Seconds; i.e. '00' to '59'"
return '%02d' % self.date.second
def S(self): def S(self):
"English ordinal suffix for the day of the month, 2 characters; i.e. 'st', 'nd', 'rd' or 'th'" "English ordinal suffix for the day of the month, 2 characters; i.e. 'st', 'nd', 'rd' or 'th'"
if self.date.day in (11, 12, 13): # Special case if self.data.day in (11, 12, 13): # Special case
return 'th' return 'th'
last = self.date.day % 10 last = self.data.day % 10
if last == 1: if last == 1:
return 'st' return 'st'
if last == 2: if last == 2:
@ -166,25 +182,22 @@ class DateFormat:
def w(self): def w(self):
"Day of the week, numeric, i.e. '0' (Sunday) to '6' (Saturday)" "Day of the week, numeric, i.e. '0' (Sunday) to '6' (Saturday)"
weekday = self.date.weekday() return (self.data.weekday() + 1) % 7
if weekday == 0:
return 6
return weekday - 1
def W(self): def W(self):
"ISO-8601 week number of year, weeks starting on Monday" "ISO-8601 week number of year, weeks starting on Monday"
# Algorithm from http://www.personal.ecu.edu/mccartyr/ISOwdALG.txt # Algorithm from http://www.personal.ecu.edu/mccartyr/ISOwdALG.txt
week_number = None week_number = None
jan1_weekday = self.date.replace(month=1, day=1).weekday() + 1 jan1_weekday = self.data.replace(month=1, day=1).weekday() + 1
weekday = self.date.weekday() + 1 weekday = self.data.weekday() + 1
day_of_year = self.z() day_of_year = self.z()
if day_of_year <= (8 - jan1_weekday) and jan1_weekday > 4: if day_of_year <= (8 - jan1_weekday) and jan1_weekday > 4:
if jan1_weekday == 5 or (jan1_weekday == 6 and isleap(self.date.year-1)): if jan1_weekday == 5 or (jan1_weekday == 6 and isleap(self.data.year-1)):
week_number = 53 week_number = 53
else: else:
week_number = 52 week_number = 52
else: else:
if isleap(self.date.year): if isleap(self.data.year):
i = 366 i = 366
else: else:
i = 365 i = 365
@ -197,18 +210,18 @@ class DateFormat:
week_number -= 1 week_number -= 1
return week_number return week_number
def Y(self):
"Year, 4 digits; e.g. '1999'"
return self.date.year
def y(self): def y(self):
"Year, 2 digits; e.g. '99'" "Year, 2 digits; e.g. '99'"
return str(self.date.year)[2:] return str(self.data.year)[2:]
def Y(self):
"Year, 4 digits; e.g. '1999'"
return self.data.year
def z(self): def z(self):
"Day of the year; i.e. '0' to '365'" "Day of the year; i.e. '0' to '365'"
doy = self.year_days[self.date.month] + self.date.day doy = self.year_days[self.data.month] + self.data.day
if self.L() and self.date.month > 2: if self.L() and self.data.month > 2:
doy += 1 doy += 1
return doy return doy
@ -218,94 +231,6 @@ class DateFormat:
is always positive.""" is always positive."""
raise NotImplementedError raise NotImplementedError
def format(self, formatstr):
result = ''
for char in formatstr:
try:
result += str(getattr(self, char)())
except AttributeError:
result += char
return result
class TimeFormat:
def __init__(self, t):
self.time = t
def a(self):
"'a.m.' or 'p.m.'"
if self.time.hour > 11:
return 'p.m.'
else:
return 'a.m.'
def A(self):
"'AM' or 'PM'"
return self.a().upper()
def B(self):
"Swatch Internet time"
raise NotImplementedError
def f(self):
"""
Time, in 12-hour hours and minutes, with minutes left off if they're zero.
Examples: '1', '1:30', '2:05', '2'
Proprietary extension.
"""
if self.time.minute == 0:
return self.g()
return '%s:%s' % (self.g(), self.i())
def g(self):
"Hour, 12-hour format without leading zeros; i.e. '1' to '12'"
if self.time.hour == 0:
return 12
if self.time.hour > 12:
return self.time.hour - 12
return self.time.hour
def G(self):
"Hour, 24-hour format without leading zeros; i.e. '0' to '23'"
return self.time.hour
def h(self):
"Hour, 12-hour format; i.e. '01' to '12'"
return '%02d' % self.g()
def H(self):
"Hour, 24-hour format; i.e. '00' to '23'"
return '%02d' % self.G()
def i(self):
"Minutes; i.e. '00' to '59'"
return '%02d' % self.time.minute
def P(self):
"""
Time, in 12-hour hours, minutes and 'a.m.'/'p.m.', with minutes left off
if they're zero and the strings 'midnight' and 'noon' if appropriate.
Examples: '1 a.m.', '1:30 p.m.', 'midnight', 'noon', '12:30 p.m.'
Proprietary extension.
"""
if self.time.minute == 0 and self.time.hour == 0:
return 'midnight'
if self.time.minute == 0 and self.time.hour == 12:
return 'noon'
return '%s %s' % (self.f(), self.a())
def s(self):
"Seconds; i.e. '00' to '59'"
return '%02d' % self.time.second
def format(self, formatstr):
result = ''
for char in formatstr:
try:
result += str(getattr(self, char)())
except AttributeError:
result += char
return result
def format(value, format_string): def format(value, format_string):
"Convenience function" "Convenience function"
df = DateFormat(value) df = DateFormat(value)

View File

@ -446,9 +446,9 @@ Built-in tag reference
<h1>Archive for {{ year }}</h1> <h1>Archive for {{ year }}</h1>
{% for date in days %} {% for day in days %}
{% ifchanged %}<h3>{{ date|date:"F" }}</h3>{% endifchanged %} {% ifchanged %}<h3>{{ day|date:"F" }}</h3>{% endifchanged %}
<a href="{{ date|date:"M/d"|lower }}/">{{ date|date:"j" }}</a> <a href="{{ day|date:"M/d"|lower }}/">{{ day|date:"j" }}</a>
{% endfor %} {% endfor %}
``ifequal`` ``ifequal``
@ -479,13 +479,78 @@ Built-in tag reference
``now`` ``now``
Display the date, formatted according to the given string. Display the date, formatted according to the given string.
Uses the same format as PHP's ``date()`` function; see http://php.net/date Uses the same format as PHP's ``date()`` function (http://php.net/date)
for all the possible values. with some custom extensions.
Sample usage:: Available format strings:
================ ====================================== =====================
Format character Description Example output
================ ====================================== =====================
a ``'a.m.'`` or ``'p.m.'`` (Note that ``'a.m.'``
this is slightly different than PHP's
output, because this includes periods
to match Associated Press style.)
A ``'AM'`` or ``'PM'``. ``'AM'``
B Not implemented.
d Day of the month, 2 digits with ``'01'`` to ``'31'``
leading zeros.
D Day of the week, textual, 3 letters. ``'Fri'``
f Time, in 12-hour hours and minutes, ``'1'``, ``'1:30'``
with minutes left off if they're zero.
Proprietary extension.
F Month, textual, long. ``'January'``
g Hour, 12-hour format without leading ``'1'`` to ``'12'``
zeros.
G Hour, 24-hour format without leading ``'0'`` to ``'23'``
zeros.
h Hour, 12-hour format. ``'01'`` to ``'12'``
H Hour, 24-hour format. ``'00'`` to ``'23'``
i Minutes. ``'00'`` to ``'59'``
I Not implemented.
j Day of the month without leading zeros. ``'1'`` to ``'31'``
l Day of the week, textual, long. ``'Friday'``
L Boolean for whether it's a leap year. ``True`` or ``False``
m Month, 2 digits with leading zeros. ``'01'`` to ``'12'``
M Month, textual, 3 letters. ``'Jan'``
n Month without leading zeros. ``'1'`` to ``'12'``
N Month abbreviation in Associated Press ``'Jan.'``, ``'Feb.'``, ``'March'``, ``'May'``
style. Proprietary extension.
O Not implemented.
P Time, in 12-hour hours, minutes and ``'1 a.m.'``, ``'1:30 p.m.'``, ``'midnight'``, ``'noon'``, ``'12:30 p.m.'``
'a.m.'/'p.m.', with minutes left off
if they're zero and the special-case
strings 'midnight' and 'noon' if
appropriate. Proprietary extension.
r Not implemented.
s Seconds, 2 digits with leading zeros. ``'00'`` to ``'59'``
S English ordinal suffix for day of the ``'st'``, ``'nd'``, ``'rd'`` or ``'th'``
month, 2 characters.
t Not implemented.
T Not implemented.
U Not implemented.
w Day of the week, digits without ``'0'`` (Sunday) to ``'6'`` (Saturday)
leading zeros.
W ISO-8601 week number of year, with ``1``, ``23``
weeks starting on Monday.
y Year, 2 digits. ``'99'``
Y Year, 4 digits. ``'1999'``
z Day of the year. ``0`` to ``365``
Z Not implemented.
Example::
It is {% now "jS F Y H:i" %} It is {% now "jS F Y H:i" %}
Note that you can backslash-escape a format string if you want to use the
"raw" value. In this example, "f" is backslash-escaped, because otherwise
"f" is a format string that displays the time. The "o" doesn't need to be
escaped, because it's not a format character.::
It is the {% "jS o\f F" %}
(Displays "It is the 4th of September" %}
``regroup`` ``regroup``
Regroup a list of alike objects by a common attribute. Regroup a list of alike objects by a common attribute.