I am inserting a date_added date time value into mysql 5.5 which does not support datetime(6) and this is causing an AssertionError when running the following unit test
foo.date_added = timezone.now()
self.assertEquals(only_foo_in_database.date_added, foo.date_added)
which leads to
AssertionError: datetime.datetime(2013, 9, 2, 6, 48, 56, tzinfo=<UTC>) != datetime.datetime(2013, 9, 2, 6, 48, 56, 677255, tzinfo=<UTC>)
How can I compare the two datetime values ignoring the microseconds?
This method takes a datetime object and returns a character string representing the date in ISO 8601 format. To get rid of the microseconds component, we have to specify the keyword 'seconds' within the isoformat function.
Use the strptime(time_str, format) function to convert a time string into a datetime object as per the corresponding format. The format codes are standard directives for mentioning the string format for parsing. For example, the %H:%M:%S format codes are for hours, minutes, and seconds.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With