1 回答
TA贡献1906条经验 获得超10个赞
您可以为此创建一个自定义序列化程序字段:
import datetime
from django.utils import timezone
from rest_framework import serializers
from rest_framework.fields import Field
class TimeWithTimezoneField(Field):
default_error_messages = {
'invalid': 'Time has wrong format, expecting %H:%M:%S%z.',
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def to_internal_value(self, value):
value_with_date = datetime.datetime.now().strftime('%Y-%m-%d') + ' ' + value
try:
parsed = datetime.datetime.strptime(value_with_date, '%Y-%m-%d %H:%M:%S%z')
except (ValueError, TypeError) as e:
pass
else:
return parsed
self.fail('invalid')
def to_representation(self, value):
if not value:
return None
if isinstance(value, str):
return value
return timezone.make_naive(value, timezone.utc).strftime("%H:%M:%S+00:00")
class ClinicSerializer(serializers.ModelSerializer):
start_at = TimeWithTimezoneField()
class Meta:
model = Clinic
fields = [
'id',
'name',
'start_at',
]
对于您的示例,start_at: 12:40:10+04:30将存储为时区感知日期时间(UTC : 08:40:10+00:00)
添加回答
举报