django中的时间戳字段

时间:2012-07-04 15:40:15

标签: python mysql django

我有一个MySQL数据库,现在我将所有日期时间字段生成为models.DateTimeField。有没有办法获得timestamp?我希望能够在创建和更新等时自动更新。

关于django的文档没有这个?

4 个答案:

答案 0 :(得分:16)

实际上有一篇关于此的非常好且内容丰富的文章。这里: http://ianrolfe.livejournal.com/36017.html

页面上的解决方案略有弃用,因此我执行了以下操作:

from django.db import models
from datetime import datetime
from time import strftime

class UnixTimestampField(models.DateTimeField):
    """UnixTimestampField: creates a DateTimeField that is represented on the
    database as a TIMESTAMP field rather than the usual DATETIME field.
    """
    def __init__(self, null=False, blank=False, **kwargs):
        super(UnixTimestampField, self).__init__(**kwargs)
        # default for TIMESTAMP is NOT NULL unlike most fields, so we have to
        # cheat a little:
        self.blank, self.isnull = blank, null
        self.null = True # To prevent the framework from shoving in "not null".

    def db_type(self, connection):
        typ=['TIMESTAMP']
        # See above!
        if self.isnull:
            typ += ['NULL']
        if self.auto_created:
            typ += ['default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP']
        return ' '.join(typ)

    def to_python(self, value):
        if isinstance(value, int):
            return datetime.fromtimestamp(value)
        else:
            return models.DateTimeField.to_python(self, value)

    def get_db_prep_value(self, value, connection, prepared=False):
        if value==None:
            return None
        # Use '%Y%m%d%H%M%S' for MySQL < 4.1
        return strftime('%Y-%m-%d %H:%M:%S',value.timetuple())

要使用它,您所要做的就是:     timestamp = UnixTimestampField(auto_created=True)

在MySQL中,列应显示为:     'timestamp' timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

唯一的缺点是它只适用于MySQL数据库。但您可以轻松地为其他人修改它。

答案 1 :(得分:2)

要自动更新插入和更新,请使用以下命令:

list_dicts = [
    {"value1": 53, "day": "Thu, 07 May 2015", "value2": 70, "type_of": "foo",},
    {"value1": 17, "day": "Thu, 07 May 2015","value2": 12,"type_of": "foo"},
    {"value1": 21, "day": "Thu, 12 May 2013", "value2": 40, "type_of": "foo"}
]

dicts_by_day = {}

for ldict in list_dicts:
    if ldict["day"] in dicts_by_day:
        dicts_by_day[ldict["day"]].append(ldict)
    else:
        dicts_by_day[ldict["day"]] = [ldict]

for day, values in dicts_by_day.items():
    print(day,values)

DateTimeField应该存储UTC(检查你的数据库设置,我从Postgres知道存在这种情况)。您可以在模板中使用created = DateTimeField(auto_now_add=True, editable=False, null=False, blank=False) last_modified = DateTimeField(auto_now=True, editable=False, null=False, blank=False) 并通过以下格式进行格式化:

l10n

自Unix Epoch以来的秒数:

{{ object.created|date:'SHORT_DATETIME_FORMAT' }}

请参阅https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#date

答案 2 :(得分:1)

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

示例模型:

from django_unixdatetimefield import UnixDateTimeField

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()

数据库:

sqlite> select created_at from mymodel;
1426967129

以下是感兴趣的源代码 - https://github.com/Niklas9/django-unixdatetimefield

免责声明:我是这个pip包的作者。

答案 3 :(得分:0)