From 93e75ec13831685fed03c35a773c8771374ecece Mon Sep 17 00:00:00 2001 From: Stephen Chisholm Date: Tue, 31 Oct 2017 06:17:08 -0300 Subject: [PATCH] Catch OverflowError for "out of range" datetimes (#5546) * Add test for #5545 * Catch OverflowError for "out of range" datetimes --- rest_framework/fields.py | 8 ++++++-- tests/test_fields.py | 1 + 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index ab8f2eb44..9cfd39995 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -1131,7 +1131,8 @@ class DateTimeField(Field): default_error_messages = { 'invalid': _('Datetime has wrong format. Use one of these formats instead: {format}.'), 'date': _('Expected a datetime but got a date.'), - 'make_aware': _('Invalid datetime for the timezone "{timezone}".') + 'make_aware': _('Invalid datetime for the timezone "{timezone}".'), + 'overflow': _('Datetime value out of range.') } datetime_parser = datetime.datetime.strptime @@ -1153,7 +1154,10 @@ class DateTimeField(Field): if field_timezone is not None: if timezone.is_aware(value): - return value.astimezone(field_timezone) + try: + return value.astimezone(field_timezone) + except OverflowError: + self.fail('overflow') try: return timezone.make_aware(value, field_timezone) except InvalidTimeError: diff --git a/tests/test_fields.py b/tests/test_fields.py index c1b99818a..2f642a77c 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -1171,6 +1171,7 @@ class TestDateTimeField(FieldValues): '2001-99-99T99:00': ['Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z].'], '2018-08-16 22:00-24:00': ['Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z].'], datetime.date(2001, 1, 1): ['Expected a datetime but got a date.'], + '9999-12-31T21:59:59.99990-03:00': ['Datetime value out of range.'], } outputs = { datetime.datetime(2001, 1, 1, 13, 00): '2001-01-01T13:00:00Z',