Skip to content

Fixed active timezone handling for non ISO8601 datetimes. #5833

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 16, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion rest_framework/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -1212,8 +1212,9 @@ def to_representation(self, value):
if output_format is None or isinstance(value, six.string_types):
return value

value = self.enforce_timezone(value)

if output_format.lower() == ISO_8601:
value = self.enforce_timezone(value)
value = value.isoformat()
if value.endswith('+00:00'):
value = value[:-6] + 'Z'
Expand Down
23 changes: 22 additions & 1 deletion tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from django.http import QueryDict
from django.test import TestCase, override_settings
from django.utils import six
from django.utils.timezone import activate, deactivate, utc
from django.utils.timezone import activate, deactivate, override, utc

import rest_framework
from rest_framework import compat, serializers
Expand Down Expand Up @@ -1296,6 +1296,27 @@ def test_current_timezone(self):
assert self.field.default_timezone() == utc


@pytest.mark.skipif(pytz is None, reason='pytz not installed')
@override_settings(TIME_ZONE='UTC', USE_TZ=True)
class TestCustomTimezoneForDateTimeField(TestCase):

@classmethod
def setup_class(cls):
cls.kolkata = pytz.timezone('Asia/Kolkata')
cls.date_format = '%d/%m/%Y %H:%M'

def test_should_render_date_time_in_default_timezone(self):
field = serializers.DateTimeField(default_timezone=self.kolkata, format=self.date_format)
dt = datetime.datetime(2018, 2, 8, 14, 15, 16, tzinfo=pytz.utc)

with override(self.kolkata):
rendered_date = field.to_representation(dt)

rendered_date_in_timezone = dt.astimezone(self.kolkata).strftime(self.date_format)

assert rendered_date == rendered_date_in_timezone


class TestNaiveDayLightSavingTimeTimeZoneDateTimeField(FieldValues):
"""
Invalid values for `DateTimeField` with datetime in DST shift (non-existing or ambiguous) and timezone with DST.
Expand Down