python - Django DateTimeField() 和 timezone.now()

标签 python django django-models

好的,当我运行功能测试时出现奇怪的时区问题。 Django 1.4, python 2.7。 MySQL 上的 DateTimeField() 中的毫秒数是否被截断?这是我唯一的理论。

模型文件

from django.db import models
from django.utils import timezone

class Search(models.Model):
    query = models.CharField(max_length=200, null=True)
    query_date = models.DateTimeField(null=True)

测试.py

from django.test import TestCase
from django.utils import timezone
from search.models import Search

class SearchModelTest(TestCase):
def test_creating_a_new_search_and_saving_it_to_the_database(self):
    # start by creating a new Poll object with its "question" set
    search = Search()
    search.query = "Test"
    search.query_date = timezone.now()

    # check we can save it to the database
    search.save()

    # now check we can find it in the database again
    all_search_in_database = Search.objects.all()
    self.assertEquals(len(all_search_in_database), 1)
    only_search_in_database = all_search_in_database[0]
    self.assertEquals(only_search_in_database, search)

    # and check that it's saved its two attributes: question and pub_date
    self.assertEquals(only_search_in_database.query, "Test")
    self.assertEquals(only_search_in_database.query_date, search.query_date)

测试失败:

self.assertEquals(only_search_in_database.query_date, search.query_date)
AssertionError: datetime.datetime(2013, 1, 16, 21, 12, 35, tzinfo=<UTC>) != datetime.datetime(2013, 1, 16, 21, 12, 35, 234108, tzinfo=<UTC>)

我认为发生的事情是在保存到数据库后毫秒数被截断了。那是对的吗?我正在运行 MySQL v 5.5。 MySQL 会截断日期吗?

最佳答案

Django ORM 转换 DateTimeFieldTimestamp在 MySQL 中。您可以通过查看执行 ./manage.py sqlall <appname> 的原始 sql 来确认这一点

在 mysql 中 timestamp不存储毫秒。

The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC.

这是 MySql 中的一个错误,似乎已在 v5.6.4 中修复,Bug

Noted in 5.6.4 changelog.

MySQL now supports fractional seconds for TIME, DATETIME, and
TIMESTAMP values, with up to microsecond precision.

关于python - Django DateTimeField() 和 timezone.now(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14368290/

相关文章:

django - 在 django 站点上工作并想知道将我的媒体存储在 nfs 挂载分区上是否明智?

django - 如何在 django admin 中的 changelist_view 中过滤查询集?

python - Django中的通用一对一关系

python - django:DetailView 如何适用于两个模型或基于类的 View 如何适用于两个模型?

python - 为什么人们在 __get__ 中将 owner 参数默认为 None?

java - 从 Java 与 Django/Celery 互操作

python - 编写python包在django内部和外部运行

django - 无法在 django 模型中添加新字段

django - 一个应用有多个模型 vs. 多个应用只有一个模型

python - 改变RNN中的 'temperature'生成文本