Django DateTimeField()和timezone.now() [英] Django DateTimeField() and timezone.now()

查看:185
本文介绍了Django DateTimeField()和timezone.now()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我正在运行功能测试时出现了奇怪的时区问题。 Django 1.4,Python 2.7。在MySQL的DateTimeField()中,毫秒是否被截断?那是我唯一的理论。

OK, weird time zone issues when I'm running function tests. Django 1.4, Python 2.7. Are milliseconds truncated in DateTimeField() on MySQL? That's the only theory I've got.

模型文件

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)

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)

测试失败,并为此:

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会截断日期吗?

I think what's happening is that the milliseconds are being truncated after saving to the database. Can that be right? I'm running MySQL v 5.5. Is MySQL truncating the date?

推荐答案

Django ORM将 DateTimeField 转换为 Timestamp 在mysql中。您可以通过执行 ./ manage.py sqlall< appname>

Django ORM converts DateTimeField to Timestamp in mysql. You can confirm that by looking at the raw sql doing ./manage.py sqlall <appname>

In mysql 时间戳不存储毫秒。

In mysql timestamp does not store milliseconds.

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中修复,错误

It is a bug in MySql which appears to be fixed in v5.6.4, The Bug

Noted in 5.6.4 changelog.

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

这篇关于Django DateTimeField()和timezone.now()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆