Compare two dates in python and ignoring microseconds

Set microsecond as 0 using datetime.datetime.replace:

>>> 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

Using datetime.timedelta:

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))

You can use assertAlmostEqual in unittest

from django.utils import timezone as tz
self.assertAlmostEqual(
    only_foo_in_database.date_added, foo.date_added,
    delta=tz.timedelta(seconds=1))

Tags:

Python