How To Compare Dates In Python?
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:
Solution 1:
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 datetime
s is a timedelta
. Datetimes are comparable with each other, as are timedelta
s.
You have 2 options:
- Subtract another
datetime
from the one you've given, and compare the resultingtimedelta
with thetimedelta
you've also given. - Convert the
timedelta
to adatetime
by adding or subtracting it to anotherdatetime
, and then compare the resultingdatetime
with thedatetime
you've given.
Solution 2:
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
Post a Comment for "How To Compare Dates In Python?"