环境

  • Django 2.2
  • Mysql 5.7

问题

不管如何设置时间格式,数据库字段保存都有微秒(我的需求是去掉微秒),如下图

image-20200923171022616

#models中定义字段
exetime = models.DateTimeField(auto_now_add=True,verbose_name='执行时间')

期间尝试了修改setings.py

DATETIME_FORMAT="%Y-%m-%d%H:%M:%S"
L10N=False
USE_TZ=False

还尝试了直接修改model

#这个应该在mysql5.6以下可用
import datetime
exetime = models.DateTimeField(auto_now_add=datetime.datetime.now().strftime('%Y-%m-%d %H:%I:%S'),verbose_name='执行时间')

以上种种皆不可行

解决

最终发现,由于django默认对mysql5.7创建datetime字段时为datetime(6),数据库保存的就一定包含微秒,所以想到两种方式,第一种改源码,把默认映射改为datetime,第二种手动更改对应数据库字段

我使用第二种手动更改数据库字段为datetime后满足需求

image-20200923172512462

如果使用第一种可以参考查看这个文件:django\db\backends\mysql\base.py

class DatabaseWrapper(BaseDatabaseWrapper):
    vendor = 'mysql'
    display_name = 'MySQL'
    # This dictionary maps Field objects to their associated MySQL column
    # types, as strings. Column-type strings can contain format strings; they'll
    # be interpolated against the values of Field.__dict__ before being output.
    # If a column type is set to None, it won't be included in the output.
    data_types = {
        'AutoField': 'integer AUTO_INCREMENT',
        'BigAutoField': 'bigint AUTO_INCREMENT',
        'BinaryField': 'longblob',
        'BooleanField': 'bool',
        'CharField': 'varchar(%(max_length)s)',
        'DateField': 'date',
        'DateTimeField': 'datetime(6)', #默认为6
        'DecimalField': 'numeric(%(max_digits)s, %(decimal_places)s)',
        'DurationField': 'bigint',
        'FileField': 'varchar(%(max_length)s)',
        'FilePathField': 'varchar(%(max_length)s)',
        'FloatField': 'double precision',
        'IntegerField': 'integer',
        'BigIntegerField': 'bigint',
        'IPAddressField': 'char(15)',
        'GenericIPAddressField': 'char(39)',
        'NullBooleanField': 'bool',
        'OneToOneField': 'integer',
        'PositiveIntegerField': 'integer UNSIGNED',
        'PositiveSmallIntegerField': 'smallint UNSIGNED',
        'SlugField': 'varchar(%(max_length)s)',
        'SmallIntegerField': 'smallint',
        'TextField': 'longtext',
        'TimeField': 'time(6)',
        'UUIDField': 'char(32)',
    }