PAYATHON 2026

Django DateTimeField 如何去除微秒并格式化显示?

数据阿明

结论

DateTimeField 保存日期时间值,不保存 03-07, 21:52 这样的显示字符串。只需调整显示格式时,可以通过模型属性格式化;如果还要在保存时去掉微秒,可以自定义字段,在 auto_now 生成时间后将微秒设为 0。

保存时去掉微秒

auto_now=True 会在保存时自动设置当前时间。因此,在模型的 save() 中提前修改 date,可能会被字段随后写入的新时间覆盖。可以在自定义字段的 pre_save() 中处理 auto_now 生成的值:

from django.db import models


class DateTimeWithoutMicrosecondsField(models.DateTimeField):
    def pre_save(self, model_instance, add):
        value = super().pre_save(model_instance, add)
        value = value.replace(microsecond=0)
        setattr(model_instance, self.attname, value)
        return value


class Event(models.Model):
    date = DateTimeWithoutMicrosecondsField(auto_now=True)

这个字段仍然保存日期时间值,只是将微秒部分设为 0。使用自定义模型字段后,需要按项目的迁移流程生成并应用数据库迁移。

显示为指定格式

可以添加一个模型属性,在需要展示时间的代码中读取它:

class Event(models.Model):
    date = DateTimeWithoutMicrosecondsField(auto_now=True)

    @property
    def formatted_date(self):
        return self.date.strftime("%m-%d, %H:%M")

例如,时间为 2026-03-07 21:52:34 时,formatted_date 返回 03-07, 21:52。strftime() 是 Python 的日期时间格式化方法。要得到指定格式的字符串,就需要对 DateTimeField 的值进行格式化。

如果只需调整显示格式,不需要在保存时去掉微秒,保留普通的 DateTimeField 并添加格式化属性即可。日期时间的存储精度可能因数据库后端而异;以上做法会在 Django 写入前将微秒明确设为 0。

备注:内容仅供参考。