Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two dates in python and ignoring microseconds

Tags:

python

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?

like image 239
Nicholas Murray Avatar asked Sep 02 '13 07:09

Nicholas Murray


People also ask

How do I get rid of microseconds Python?

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.

How do I find the difference between two dates and seconds in Python?

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.


2 Answers

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))
like image 124
falsetru Avatar answered Oct 12 '22 15:10

falsetru


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))
like image 37
Xavier-Lam Avatar answered Oct 12 '22 13:10

Xavier-Lam