-
-
Notifications
You must be signed in to change notification settings - Fork 7k
Description
Checklist
- I have verified that that issue exists against the
master
branch of Django REST framework. - I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- This is not a usage question. (Those should be directed to the discussion group instead.)
- This cannot be dealt with as a third party library. (We prefer new functionality to be in the form of third party libraries where possible.)
- I have reduced the issue to the simplest possible case.
- I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
Steps to reproduce / Actual behavior
DRF's DateTimeField
has no option to keep a datetime
's original timezone information during serialization/deserialization. Here a serialization example:
- Set
USE_TZ = True
andTIME_ZONE = "UTC"
. - Consider the following
datetime
object:dt = datetime.datetime(2018, 9, 4, 7, 30, tzinfo=<DstTzInfo 'Europe/Berlin' CEST+2:00:00 DST>)
. - Serialize it with
serializers.DateTimeField().to_representation(dt)
This yields '2018-09-04T05:30:00Z'
which represents the datetime in the UTC timezone.
Expected behavior
The serialized datetime is correct, however, does not contain any information about the original timezone. DRF's DateTimeField
should provide an option to preserve this timezone info by instead serializing to: '2018-09-04T07:30:00+02:00'
.
Why?
While the returned string is correct, there are use cases in which a frontend (API consumer) might want to display the datetime in the timezone it was originally in. For example, a flight ticket search engine generally displays any datetimes in the local timezone of the airport. So instead of displaying the departure time of a flight in UTC it generally displays it in the timezone of the airport. This is however not possible with the current implementation of DateTimeField
.
Possible Solution
Would the maintainers be open to a PR that adds an option to the DateTimeField
that would allow it to deserialize / serialize datetimes while keeping their original datetime? I can go into depth about other use cases and possible implementations, however, I would like to first know if this idea is welcome in general.
This problem was already mentioned in #3732 and generally well received ("I’m really happy to take a PR on this."), however, the issue originally addressed another problem and was subsequently closed before the issue I am mentioning here was addressed.