且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

django - 使datetimefield接受unix时间戳

更新时间:2023-01-24 20:08:39

pip包django- unixdatetimefield提供了一个UnixDateTimeField字段,您可以为此开箱即用( https:// pypi)。 python.org/pypi/django-unixdatetimefield/ )。



示例模型:

  from django_unixdatetimefield import UnixDateTimeField 

class MyModel(models.Model):
created_at = UnixDateTimeField()
pre>

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 DataTimeField

i.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.