Django DateTimeField()和timezone.now()

ghi*_*ion 7 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)
Run Code Online (Sandbox Code Playgroud)

test.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)
Run Code Online (Sandbox Code Playgroud)

测试失败了:

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>)
Run Code Online (Sandbox Code Playgroud)

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

Pra*_*kar 11

Django ORM转换DateTimeFieldTimestampmysql.您可以通过查看原始sql来确认./manage.py sqlall <appname>

在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.
Run Code Online (Sandbox Code Playgroud)

这是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.
Run Code Online (Sandbox Code Playgroud)

  • 非常感激.有时我想知道为什么我继续使用MySQL. (4认同)

Ell*_*ski 5

Django 1.8现在支持毫秒.

以前,当使用MySQL后端时,Django会截断日期时间和时间值的小数秒.现在它让数据库决定是否应该删除该部分值