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

2 Comments

    • >>> d1=datetime.datetime(2015,1,1,23,12,40)
      >>> d2=datetime.datetime(2015,1,1,23,17,38)
      >>> d3=datetime.datetime(2015,1,1,23,17,42)
      >>> d5=datetime.timedelta(minutes=5)
      >>> d1+d5>d3
      False
      >>> d1+d5>d2
      True

Leave a Reply

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.