【问题标题】:Timestamp before creating model instance not less than model instance creation timestamp django创建模型实例前的时间戳不小于模型实例创建时间戳django
【发布时间】:2015-05-31 15:40:14
【问题描述】:

我正在对某个模型进行一些测试,所以我创建了一个变量 before_creation = datetime.now()

我的模型有一个字段定义为

date_created = models.DateTimeField(auto_now_add=True)

在我的测试中这是怎么做的

before_creation create_model_instance 然后测试before_creation 小于mymodel.date_created,在我看来应该通过,但它失败并显示以下消息AssertionError: datetime.datetime (some timestamp) not less than datetime.datetime ((some other timestamp)。这是一个错误吗?我试过切换到时区,但没有成功。

【问题讨论】:

  • 请出示一些代码。

标签: python django sqlite datetime django-models


【解决方案1】:

如果差异以微秒为单位,则您的数据库可能会截断这些差异。因此,如果 before_creation 位于 12:00:00.005 且 date_created 位于 12:00:00.008,则 date_created 将返回为 12:00:00。然后你会得到before_creation > date_created

检查以确保不是这种情况。或使用:

before_creation = datetime.now().replace(microseconds=0)

并将您的断言更改为小于或等于。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-19
    • 1970-01-01
    • 2023-03-23
    • 2019-01-06
    • 2011-08-02
    • 2013-02-11
    • 2017-03-04
    相关资源
    最近更新 更多