How to compare dates in Python?

André picture André · Oct 24, 2011 · Viewed 8.2k times · Source

I need to see if a date has more than X days. How can I do this in Python?

I have tested something like:

if datetime.date(2010, 1, 12) > datetime.timedelta(3):

I got the error:

TypeError: can't compare datetime.date to datetime.timedelta

Any clue on how to achieve this?

Answer

Matt Joiner picture Matt Joiner · Oct 24, 2011

You can't compare a datetime to a timedelta. A timedelta represents a duration, a datetime represents a specific point in time. The difference of two datetimes is a timedelta. Datetimes are comparable with each other, as are timedeltas.

You have 2 options:

  • Subtract another datetime from the one you've given, and compare the resulting timedelta with the timedelta you've also given.
  • Convert the timedelta to a datetime by adding or subtracting it to another datetime, and then compare the resulting datetime with the datetime you've given.