我将一个date_added日期时间值插入到不支持datetime(6)的mysql 5.5中,这会在运行以下单元测试时导致AssertionError
foo.date_added = timezone.now()
self.assertEquals(only_foo_in_database.date_added, foo.date_added)
导致
AssertionError: datetime.datetime(2013, 9, 2, 6, 48, 56, tzinfo=<UTC>) != datetime.datetime(2013, 9, 2, 6, 48, 56, 677255, tzinfo=<UTC>)
如何比较忽略微秒的两个日期时间值?
答案 0 :(得分:12)
使用datetime.datetime.replace
将微秒设置为0
:
>>> d = datetime.datetime.now()
>>> d
datetime.datetime(2013, 9, 2, 16, 25, 59, 444433)
>>> d.replace(microsecond=0)
datetime.datetime(2013, 9, 2, 16, 25, 59)
self.assertEquals(only_foo_in_database.date_added.replace(microsecond=0),
foo.date_added.replace(microsecond=0))
<强> ALTERNATIVE 强>
d1 = datetime.datetime(2013,9,2,6,48,56)
d2 = datetime.datetime(2013,9,2,6,48,56,677255)
self.assertTrue(abs(d1 - d2) < datetime.timedelta(seconds=1))
答案 1 :(得分:2)
您可以在unittest中使用assertAlmostEqual
from django.utils import timezone as tz
self.assertAlmostEqual(
only_foo_in_database.date_added, foo.date_added,
delta=tz.timedelta(seconds=1))