Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why datetime cannot compare?

my C# unit test has the following statement:

Assert.AreEqual(logoutTime, log.First().Timestamp); 

Why it is failed with following information:

Assert.AreEqual failed. Expected:<4/28/2010 2:30:37 PM>. Actual:<4/28/2010 2:30:37 PM>. 

Are they not the same?

Update:

Use this if you only care to second:

Assert.AreEqual(logoutTime.ToString(), log.First().Timestamp.ToString());

like image 644
5YrsLaterDBA Avatar asked Apr 28 '10 18:04

5YrsLaterDBA


People also ask

Can we compare date with datetime?

Use datetime. datetime. date() can also be used to compare two dates. The datetime.

Can you compare datetime Python?

Comparing dates is quite easy in Python. Dates can be easily compared using comparison operators (like <, >, <=, >=, != etc.).

How can I compare two datetime strings?

If both the date/time strings are in ISO 8601 format (YYYY-MM-DD hh:mm:ss) you can compare them with a simple string compare, like this: a = '2019-02-12 15:01:45.145' b = '2019-02-12 15:02:02.022' if a < b: print('Time a comes before b.

How do you compare a timestamp in python?

Comparison between pandas timestamp objects is carried out using simple comparison operators: >, <,==,< = , >=. The difference can be calculated using a simple '–' operator. Given time can be converted to pandas timestamp using pandas. Timestamp() method.


2 Answers

Have you verified that the number of ticks/milliseconds are equal?

If you do DateTime.Now() twice back to back, they will appear to be the same number down to the minute and probably even down to the second, but they will often vary by ticks. If you want to check equality only to the minute, compare each DateTime only to that degree. For information on rounding DateTimes, see here


A note about resolution:

The Now property is frequently used to measure performance. However, because of its low resolution, it is not suitable for use as a benchmarking tool. A better alternative is to use the Stopwatch class.

like image 57
Dinah Avatar answered Oct 04 '22 20:10

Dinah


The Assert fail method is probably calling ToString() on the DateTime which returns a truncated, human-readable form of the date without the milliseconds component. This is why it appears they are equal when, in fact, the DateTime object has a precision of a 100-nanosecond unit (known as a Tick). That means it is highly unlikely two DateTime objects will have the exact same value. To compare you probably want to truncate the value, perhaps by formatting the date to the fidelity you require.

like image 37
Dan Diplo Avatar answered Oct 04 '22 18:10

Dan Diplo