代码之家  ›  专栏  ›  技术社区  ›  Gabi Purcaru BornCoder

更改python中的默认日期打印格式

  •  1
  • Gabi Purcaru BornCoder  · 技术社区  · 14 年前

    Can I change the default __str__() function of the datetime.datetime object? By default, it returns something like '2010-06-28 12:43:56.985790' , and i need it to print something like '2010-06-28T12:44:21.241228' (which is the isoformat() function).

    I need this for JSON serializing of a django model.

    我的模型是:

    
    class Transport(models.Model):
        user = models.ForeignKey(User)
        source = models.ForeignKey(Marker, related_name="source_marker")
        destination = models.ForeignKey(Marker, related_name="destination_marker")
        object = models.CharField(choices=possesion_choices, max_length=2**6)
        quantity = models.IntegerField()
        time_sent = models.DateTimeField()
        time_arrived = models.DateTimeField()
    
    

    And when i serialize it (using the wadofstuff module ), it prints something like

    
    print serializers.serialize('json', Transport.objects.all(), relations=('source', 'destination',)  indent=4)
    [
        {
            "pk": 1, 
            "model": "main.transport", 
            "fields": {
                [.. bla bla ..]
                "time_sent": "2010-06-28 12:18:05", 
                "time_arrived": "2010-06-28 12:38:36", 
                [.. bla bla ..]
            }
        }
    ]
    
    
    1 回复  |  直到 14 年前
        1
  •  2
  •   Daniel Roseman    14 年前

    Django uses a field's value_to_string 方法在序列化程序中提供字符串表示形式。因此,可以定义一个覆盖此方法的自定义字段子类:

    class MyDateTimeField(DateTimeField)
        def value_to_string(self, obj):
            val = self._get_val_from_obj(obj)
            if val is None:
                data = ''
            else:
                data = val.isoformat()
            return data
    

    编辑

    Aargh, looks like I was looking in completely the wrong place. 这个 serializers.python.Serializer.handle_field 方法实际上检查日期时间字段,并将其通过未更改的JSON编码器传递。所以我们需要重写的就是编码器。

    class MyJSONEncoder(DjangoJSONEncoder):
        def default(self, o):
            if isinstance(o, datetime.datetime):
                return o.isoformat()
            else:
                return super(MyJSONEncoder, self).default(o)
    

    不幸的是, wadofstuff hardcodes the original DjangoJSONEncoder, so we'll need to override the serializer too.

    from wadofstuff.django.serializers.json import Serializer
    class BetterSerializer(Serializer):
        """
        Convert a queryset to JSON.
        """
        def end_serialization(self):
            """Output a JSON encoded queryset."""
            self.options.pop('stream', None)
            self.options.pop('fields', None)
            self.options.pop('excludes', None)
            self.options.pop('relations', None)
            self.options.pop('extras', None)
            simplejson.dump(self.objects, self.stream, cls=MyJSONEncoder,
                **self.options)