Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strict comparison of DateTime Objects

I am doing a strict comparison on a list of objects, just to identify objects which might have changed, like:

if ($oldValue !== $newValue)

in some cases $oldValue and $newValue are DateTime objects.

Debugging my app I am getting the following output for my two values just before comparing them:

DateTime Object ( [date] => 2017-04-24 00:00:00.000000 [timezone_type] => 3 [timezone] => UTC )

DateTime Object ( [date] => 2017-04-24 00:00:00.000000 [timezone_type] => 3 [timezone] => UTC )

Why is my comparison/condition still true?

like image 733
LBA Avatar asked Apr 24 '17 15:04

LBA


People also ask

Is there a === in Python?

The == operator compares the value or equality of two objects, whereas the Python is operator checks whether two variables point to the same object in memory. In the vast majority of cases, this means you should use the equality operators == and != , except when you're comparing to None .

Does Python have a strict equality operator?

Python's equal comparator is strict except for when comparing 1 to True, and 0 to False, and it doesn't matter if the value for 1 or 0 is of type float, decimal. Decimal, or long. Zero of any numeric type, for example, 0, 0L, 0.0, 0j is always False.

What does DateTime compare do?

Compares two instances of DateTime and returns an integer that indicates whether the first instance is earlier than, the same as, or later than the second instance.

How do I compare two DateTime values in Python?

You can use equal to comparison operator = to check if one datetime object is has same value as other.


1 Answers

When comparing objects in PHP, the === operator does not compare values. It compares instances. This means unless both objects point to the same object, they are not strictly equal.

When using the comparison operator (==), object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values (values are compared with ==), and are instances of the same class.

When using the identity operator (===), object variables are identical if and only if they refer to the same instance of the same class.

like image 169
John Conde Avatar answered Oct 03 '22 08:10

John Conde