diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 2a08e09ffe..d4496a2e80 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -1072,10 +1072,24 @@ def to_representation(self, value): return value if output_format.lower() == ISO_8601: + if isinstance(value, six.string_types): + format_strings = (format_prefix + timezone_extension + for format_prefix in ('%Y-%m-%dT%H:%M', '%Y-%m-%dT%H:%M:%S', '%Y-%m-%dT%H:%M:%S.%f') + for timezone_extension in ('', '%Z', '%z')) + for format_string in format_strings: + try: + value = datetime.datetime.strptime(value, format_string) + break + except ValueError: + pass + else: + raise ValueError('DateTime String %s did not match any valid format string.' % value) + value = value.isoformat() if value.endswith('+00:00'): value = value[:-6] + 'Z' return value + return value.strftime(output_format) diff --git a/tests/test_fields.py b/tests/test_fields.py index cefb45605a..b31f59c7f3 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -978,6 +978,16 @@ class TestDateTimeField(FieldValues): outputs = { datetime.datetime(2001, 1, 1, 13, 00): '2001-01-01T13:00:00', datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()): '2001-01-01T13:00:00Z', + '2001-01-01T01:01': '2001-01-01T01:01:00', + '2001-01-01T01:01:01': '2001-01-01T01:01:01', + '2001-01-01T01:01:01.01': '2001-01-01T01:01:01.010000', + # Caveat of Python 2's datetime module does not allow '+HHMM' ISO-8601 strings to be parsed in Python 2's strptime + '2001-01-01T01:01+0100' if six.PY3 else None: '2001-01-01T01:01:00+01:00' if six.PY3 else None, + '2001-01-01T01:01:01+0100' if six.PY3 else None: '2001-01-01T01:01:01+01:00' if six.PY3 else None, + '2001-01-01T01:01:01.01+0100' if six.PY3 else None: '2001-01-01T01:01:01.010000+01:00' if six.PY3 else None, + '2001-01-01T01:01UTC': '2001-01-01T01:01:00', + '2001-01-01T01:01:01UTC': '2001-01-01T01:01:01', + '2001-01-01T01:01:01.01UTC': '2001-01-01T01:01:01.010000', None: None, '': None, } pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy