django - 使datetimefield接受unix时间戳 [英] django - make datetimefield accept unix timestamp
问题描述
我想让模型的DateTimefield接受unix时间戳(以秒为单位)的值。
我发现这个,但是被接受的解决方案不起作用?
DataTimeField中的unixtimestamp输入
ie我看不到如何添加%s作为输入格式将会起作用,特别是当标准datetime字段的to_python()的代码不包含处理unix时间戳的任何逻辑时。
如果有一个设置允许我做这个很棒的。
否则,我想我想要的是子类化DateTimeField,并以某种方式自动将int转换为datetime对象,当我设置值。我想在保存之前进行此操作,而不是覆盖save(),因为我在检索此字段的值时希望保持一致。即当我拿出这个值时,我不想担心如果我有一个datetime对象或一个int,不管实例是否被保存。
我看着django.db.models.fields的源码,对我来说并不明显。
pip包django- unixdatetimefield提供了一个UnixDateTimeField字段,您可以为此开箱即用( https:// pypi)。 python.org/pypi/django-unixdatetimefield/ )。
示例模型:
from django_unixdatetimefield import UnixDateTimeField
pre>
class MyModel(models.Model):
created_at = UnixDateTimeField()
Python ORM查询:
>>> m = MyModel()
>>> m.created_at = datetime.datetime(2015,2,21,19,38,32,209148)
>>> m.save()
数据库:
源码>从mymodel中选择created_at;
1426967129
如果感兴趣,这里是源代码 - https://github.com/Niklas9/django-unixdatetimefield 。
免责声明:我是这个点包的作者。
i'd like to make the DateTimefield of models accept unix timestamp (in seconds) values.
I found this but the acepted solution doesn't work?
unixtimestamp input in DataTimeFieldi.e. i don't see how adding '%s' as an input format will work, especially when the code for to_python() of the standard datetime field doesn't include any logic for handling unix timestamps.
If there is a setting that allows me to do this great.
Otherwise, what I think i want is to subclass DateTimeField and somehow automatically convert the int to a datetime object when i set the value. I want to do this before saving instead of overriding save() because i want consistency when retrieving the value of this field. i.e. when I take the value out, I don't want to worry about if i have a datetime object or an int regardless of if the instance has been saved or not.I looked at source of django.db.models.fields and it's not apparent to me.
解决方案The pip package django-unixdatetimefield provides a UnixDateTimeField field that you can use for this out of the box (https://pypi.python.org/pypi/django-unixdatetimefield/).
Example model:
from django_unixdatetimefield import UnixDateTimeField class MyModel(models.Model): created_at = UnixDateTimeField()
Python ORM query:
>>> m = MyModel() >>> m.created_at = datetime.datetime(2015, 2, 21, 19, 38, 32, 209148) >>> m.save()
Database:
sqlite> select created_at from mymodel; 1426967129
Here's the source code if interested - https://github.com/Niklas9/django-unixdatetimefield.
Disclaimer: I'm the author of this pip package.
这篇关于django - 使datetimefield接受unix时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!