python - django 中的时间戳字段

标签 python mysql django

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

django 的文档没有这个?

最佳答案

实际上有一篇关于此的非常好且内容丰富的文章。这里: 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())

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

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

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

关于python - django 中的时间戳字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11332107/

相关文章:

python - 如何对浮点输出执行单元测试? - Python

mysql - 查找所有不相关的行

mysql - SQL查找属于圆的坐标

MySQL:如果字段为空,则不显示特定数据

django - S3Boto存储和单元测试

python - 覆盖rest-auth注册以向我的后端添加额外的字段

python - 如何比较 Django 模板中的日期

python - 安装 keras 后,anaconda 提示符始终以这些命令集启动

python - 如何在 Pyramid 模板中检查经过身份验证的用户?

python - 将一个文件中的特定行写入另一个文件