How can I compare a date and a datetime in Python?
Use the .date()
method to convert a datetime to a date:
if item_date.date() > from_date:
Alternatively, you could use datetime.today()
instead of date.today()
. You could use
from_date = from_date.replace(hour=0, minute=0, second=0, microsecond=0)
to eliminate the time part afterwards.
I am trying to compare date which are in string format like '20110930'
benchMark = datetime.datetime.strptime('20110701', "%Y%m%d")
actualDate = datetime.datetime.strptime('20110930', "%Y%m%d")
if actualDate.date() < benchMark.date():
print True
Here is another take which preserves information in case both the inputs are datetimes and not dates, "stolen" from a comment at can't compare datetime.datetime to datetime.date ... convert the date to a datetime using this construct:
datetime.datetime(d.year, d.month, d.day)
Suggestion:
from datetime import datetime
def ensure_datetime(d):
"""
Takes a date or a datetime as input, outputs a datetime
"""
if isinstance(d, datetime):
return d
return datetime.datetime(d.year, d.month, d.day)
def datetime_cmp(d1, d2):
"""
Compares two timestamps. Tolerates dates.
"""
return cmp(ensure_datetime(d1), ensure_datetime(d2))