好的,当我运行功能测试时出现奇怪的时区问题。 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 转换 DateTimeField
至 Timestamp
在 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/