mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-08-08 06:14:47 +03:00
DateTimeField to_representation can handle strings. Fixes #4013.
This commit is contained in:
parent
c1802db1eb
commit
ead620521e
|
@ -1072,10 +1072,24 @@ class DateTimeField(Field):
|
||||||
return value
|
return value
|
||||||
|
|
||||||
if output_format.lower() == ISO_8601:
|
if output_format.lower() == ISO_8601:
|
||||||
|
if isinstance(value, str):
|
||||||
|
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()
|
value = value.isoformat()
|
||||||
if value.endswith('+00:00'):
|
if value.endswith('+00:00'):
|
||||||
value = value[:-6] + 'Z'
|
value = value[:-6] + 'Z'
|
||||||
return value
|
return value
|
||||||
|
|
||||||
return value.strftime(output_format)
|
return value.strftime(output_format)
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -978,6 +978,15 @@ class TestDateTimeField(FieldValues):
|
||||||
outputs = {
|
outputs = {
|
||||||
datetime.datetime(2001, 1, 1, 13, 00): '2001-01-01T13:00:00',
|
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',
|
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',
|
||||||
|
'2001-01-01T01:01+0100': '2001-01-01T01:01:00+01:00',
|
||||||
|
'2001-01-01T01:01:01+0100': '2001-01-01T01:01:01+01:00',
|
||||||
|
'2001-01-01T01:01:01.01+0100': '2001-01-01T01:01:01.010000+01:00',
|
||||||
|
'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: None,
|
||||||
'': None,
|
'': None,
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue
Block a user