1
0
mirror of https://github.com/django/django.git synced 2024-12-23 01:25:58 +00:00

Added support for datetime.date to DateFormat.r().

This commit is contained in:
Nick Pope 2021-05-13 13:52:18 +01:00 committed by Mariusz Felisiak
parent 41ca2afd1c
commit 65477fd7da
2 changed files with 17 additions and 11 deletions

View File

@ -265,16 +265,14 @@ class DateFormat(TimeFormat):
def r(self): def r(self):
"RFC 5322 formatted date; e.g. 'Thu, 21 Dec 2000 16:01:07 +0200'" "RFC 5322 formatted date; e.g. 'Thu, 21 Dec 2000 16:01:07 +0200'"
if type(self.data) is date: value = self.data
raise TypeError( if not isinstance(value, datetime):
"The format for date objects may not contain time-related " # Assume midnight in default timezone if datetime.date provided.
"format specifiers (found 'r')." default_timezone = get_default_timezone()
) value = datetime.combine(value, time.min).replace(tzinfo=default_timezone)
if is_naive(self.data): elif is_naive(value):
dt = make_aware(self.data, timezone=self.timezone) value = make_aware(value, timezone=self.timezone)
else: return format_datetime_rfc5322(value)
dt = self.data
return format_datetime_rfc5322(dt)
def S(self): def S(self):
""" """

View File

@ -200,7 +200,7 @@ class DateFormatTests(SimpleTestCase):
def test_invalid_time_format_specifiers(self): def test_invalid_time_format_specifiers(self):
my_birthday = date(1984, 8, 7) my_birthday = date(1984, 8, 7)
for specifier in ["a", "A", "f", "g", "G", "h", "H", "i", "P", "r", "s", "u"]: for specifier in ["a", "A", "f", "g", "G", "h", "H", "i", "P", "s", "u"]:
with self.subTest(specifier=specifier): with self.subTest(specifier=specifier):
msg = ( msg = (
"The format for date objects may not contain time-related " "The format for date objects may not contain time-related "
@ -237,6 +237,14 @@ class DateFormatTests(SimpleTestCase):
with self.subTest(time=t): with self.subTest(time=t):
self.assertEqual(dateformat.time_format(t, "P"), expected) self.assertEqual(dateformat.time_format(t, "P"), expected)
def test_r_format_with_date(self):
# Assume midnight in default timezone if datetime.date provided.
dt = date(2022, 7, 1)
self.assertEqual(
dateformat.format(dt, "r"),
"Fri, 01 Jul 2022 00:00:00 +0200",
)
def test_r_format_with_non_en_locale(self): def test_r_format_with_non_en_locale(self):
# Changing the locale doesn't change the "r" format. # Changing the locale doesn't change the "r" format.
dt = datetime(1979, 7, 8, 22, 00) dt = datetime(1979, 7, 8, 22, 00)