将日期时间序列化为整数时间戳 [英] serialize a datetime as an integer timestamp
本文介绍了将日期时间序列化为整数时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望django rest在序列化时不要将我的DateTime模型字段转换为字符串日期表示形式.
I would like for django rest to not convert my DateTime model field into a string date represtation when serializing it.
response_date = serializers.DateTimeField(source="updated_at")
我希望这样出现
1411880508
1411880508
不是
"2014-09-28T05:01:48.123"
"2014-09-28T05:01:48.123"
推荐答案
You'll want to write a custom serializer field, like so:
class TimestampField(serializers.Field):
def to_native(self, value):
epoch = datetime.datetime(1970,1,1)
return int((value - epoch).total_seconds())
要支持您想从 WritableField
继承的写入操作,还需要实现 from_native()
.
To support write operations you'd want to inherit from WritableField
and also implement from_native()
.
编辑DRF 3.x&Python 3.8:
class TimestampField(serializers.Field):
def to_representation(self, value):
return value.timestamp()
如果您想要JavaScript样式的时间戳记:
If you want a JavaScript style timestamp:
class JsTimestampField(serializers.Field):
def to_representation(self, value):
return round(value.timestamp()*1000)
这篇关于将日期时间序列化为整数时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文