DateTimeField输入格式无法解析str

时间:2015-10-18 16:21:11

标签: python django-models django-rest-framework python-datetime

我有以下字段:

from rest_framework import serializers
class ActivitySerializer(serializers.Serializer):
    startDate = serializers.DateTimeField(input_formats=['%Y-%m-%d %H:%M:%S %z'])

activity = {u'startDate': "2015-10-18 15:11:50 +0000"}
serializer = ActivitySerializer(data=activity)
serializer.is_valid() # False
serializer.errors
# {'startDate': [u'Datetime has wrong format. Use one of these formats instead: YYYY-MM-DD hh:mm:ss [+HHMM|-HHMM].']}

有关为什么我正在使用的日期时间字符串与该格式不匹配的任何想法?鉴于datetime字符串,解析它的正确格式字符串是什么?

1 个答案:

答案 0 :(得分:0)

我刚刚创建了一个新字段ActivityStartDateField,并实现了自定义to_internal_value。我很惊讶我无法使用内置的DateTimeField

class ActivityStartDateField(serializers.Field):
    def to_representation(self, obj):
        return str(obj)

    def to_internal_value(self, data):
        dt = arrow.get(data,'YYYY-MM-DD HH:mm:ss Z').datetime
        return dt