Python date comparison

Comparing dates (or datetime objects) in Python is very easy. The basic comparison operators (==, !=, <>, >, <, >=, <=) are overloaded for the datetime object, so comparing dates is very intuitive and quick.

For two dates:

>>> import datetime
>>> d1 = datetime.datetime(2015, 1, 1, 0, 0)
>>> d2 = datetime.datetime(2014, 1, 1, 0, 0)

To check whether the dates are the same:

>>> d1 == d2
False

To check whether two dates are not the same:

>>> d1 != d2
True

>>> d1 <> d2
True

To check whether a date is larger (younger):

>>> d1 > d2
True

To check whether a date is larger (younger) or equal:

>>> d1 >= d2
True

To check whether a date is smaller (older):

>>> d1 < d2
False

To check whether a date is smaller (older) or equal:

>>> d1 <= d2
False

1 Comment Python date comparison

Leave A Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.