2

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?

1
  • 2
    "I need to see if a date have more than X days." What does that mean? That the day of month is greater than X? To get the day of month for a date, use the day attribute. if thedate.day > X: Commented Oct 24, 2011 at 8:45

2 Answers 2

7

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.
Sign up to request clarification or add additional context in comments.

Comments

1

Comparing apples and oranges is always very hard! You are trying to compare "January 12, 2010" (a fixed point in time) with "3 hours" (a duration). There is no sense in this.

If what you are asking is "does my datetime fall after the nth day of the month" then you can do :

my_important_date = datetime.now()

if my_important_date.day > n:
    pass #do you important things

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.