ios Django休息框架日期时间字段格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33287493/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 08:04:13  来源:igfitidea点击:

Django rest framework datetime field format

iosdjangoswiftdjango-rest-framework

提问by Mirza Delic

I use this field:

我使用这个字段:

ordered_date = serializers.DateTimeField(format="iso-8601", required=False, read_only=True)

and when i go to rest url, i get time:

当我去休息网址时,我有时间:

"ordered_date": "2015-10-22T19:50:08"

but when i serialize date and then send it with GCM push, it adds miliseconds(2015-10-22T19:53:43.777171), how can i fix this, i need only one format to use, not mix with these two.

但是当我序列化日期然后使用 GCM 推送发送它时,它会增加毫秒(2015-10-22T19:53:43.777171),我该如何解决这个问题,我只需要使用一种格式,而不是将这两种格式混合使用。

How can i fix this?

我怎样才能解决这个问题?

I use this for ios swift app.

我将它用于 ios swift 应用程序。

回答by Rahul Gupta

You can specify a formatparameter to the ordered_datefield having value as a string representing the output format.

您可以formatordered_date字段指定一个参数,其值为代表输出格式的字符串。

ordered_date = serializers.DateTimeField(format="%Y-%m-%dT%H:%M:%S", required=False, read_only=True)

For example:

例如:

In [1]: from rest_framework import  serializers

In [2]: from datetime import datetime

In [3]: class XYZSerializer(serializers.Serializer): # define a serializer with a datetime field
   ...:     ordered_date = serializers.DateTimeField(format="%Y-%m-%dT%H:%M:%S")
   ...:    

In [4]: x = XYZSerializer(data={'ordered_date':datetime.now()})

In [5]: x.is_valid()
Out[5]: True

In [6]: x.data # contains the datetime field in the desired format
Out[6]: OrderedDict([('ordered_date', '2015-10-22T18:17:51')])