Is it possible to use DRF's datetime picker and include the UTC offset for timestamps in the response JSON?
I am trying to use the Web browsable API in Django Rest Framework. I have objects with timestamp data in this format, "2025-05-08T22:02:58.869000-07:00". But the required format for Django's datetime picker does not support UTC offset or the last three significant digits for microseconds as shown below:
I can trim the input data to satisfy the datetime picker like this:
class MillisecondDateTimeField(serializers.DateTimeField):
def to_representation(self, value):
return value.astimezone().strftime("%Y-%m-%dT%H:%M:%S") + ".{:03d}".format(
int(value.microsecond / 1000)
)
But then the UTC offset is also missing from the timestamp in the POST/PUT response.
{
...
"start_datetime": "2025-05-08T22:02:58.869",
...
}
How can I make the value for "start_datetime" appear as "2025-05-08T22:02:58.869000-07:00" in the JSON response from POST/PUT while also using "2025-05-08T22:02:58.869" in the datetime picker? I have been researching online and trying for days.
If you want to accept a simple input like "2025-05-08T22:02:58.869". But return a full ISO 8601 string with time zone in the API response (like "2025-05-08T22:02:58.869000-07:00"). You can use a custom serializer field. I recommend to check out following DRF API Guide about overriding serialization and deserialization behavior
import pytz
from rest_framework import serializers
from datetime import datetime
class CustomDateTimeFieldSerializer(serializers.DateTimeField):
def to_representation(self, value):
# Return full ISO 8601 string with offset
return value.isoformat()
def to_internal_value(self, value):
if isinstance(value, datetime):
return value
if isinstance(value, str):
try:
# Accept format from datetime picker (no timezone)
dt = datetime.strptime(value, "%Y-%m-%dT%H:%M:%S.%f")
return pytz.UTC.localize(dt) # or your preferred timezone
except ValueError:
pass
return super().to_internal_value(value)
# Use It in Your Serializer
class Serializer(serializers.ModelSerializer):
start_datetime = CustomDateTimeFieldSerializer()
class Meta:
model = Model
fields = '__all__'