From 65477fd7dae9e2c9f4a241b2eddf25bdb1ceeb0f Mon Sep 17 00:00:00 2001 From: Nick Pope Date: Thu, 13 May 2021 13:52:18 +0100 Subject: [PATCH] Added support for datetime.date to DateFormat.r(). --- django/utils/dateformat.py | 18 ++++++++---------- tests/utils_tests/test_dateformat.py | 10 +++++++++- 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/django/utils/dateformat.py b/django/utils/dateformat.py index adf748b21c..103bff7aae 100644 --- a/django/utils/dateformat.py +++ b/django/utils/dateformat.py @@ -265,16 +265,14 @@ class DateFormat(TimeFormat): def r(self): "RFC 5322 formatted date; e.g. 'Thu, 21 Dec 2000 16:01:07 +0200'" - if type(self.data) is date: - raise TypeError( - "The format for date objects may not contain time-related " - "format specifiers (found 'r')." - ) - if is_naive(self.data): - dt = make_aware(self.data, timezone=self.timezone) - else: - dt = self.data - return format_datetime_rfc5322(dt) + value = self.data + if not isinstance(value, datetime): + # Assume midnight in default timezone if datetime.date provided. + default_timezone = get_default_timezone() + value = datetime.combine(value, time.min).replace(tzinfo=default_timezone) + elif is_naive(value): + value = make_aware(value, timezone=self.timezone) + return format_datetime_rfc5322(value) def S(self): """ diff --git a/tests/utils_tests/test_dateformat.py b/tests/utils_tests/test_dateformat.py index 4402048f3a..9563790b20 100644 --- a/tests/utils_tests/test_dateformat.py +++ b/tests/utils_tests/test_dateformat.py @@ -200,7 +200,7 @@ class DateFormatTests(SimpleTestCase): 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", "r", "s", "u"]: + for specifier in ["a", "A", "f", "g", "G", "h", "H", "i", "P", "s", "u"]: with self.subTest(specifier=specifier): msg = ( "The format for date objects may not contain time-related " @@ -237,6 +237,14 @@ class DateFormatTests(SimpleTestCase): with self.subTest(time=t): 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): # Changing the locale doesn't change the "r" format. dt = datetime(1979, 7, 8, 22, 00)