I have 2 datetime objects. One only has the date and the other one has date & time. I want to compare the dates only (and not the time). This is what I have:
d2=datetime.date(d1.year,d1.month,d1.day)
print d2 == d1.date
It prints out false. Any idea why?
Thank you!
Fortunately you can use the INT() function in Excel to extract just the date from a datetime value, which allows you to easily compare dates while ignoring the time.
The DateTime Object has a built in function called date(). You can use this to get the date only of the datetime object. You can now use this current_time_only_date as do any equality operation you want.
To remove the time from a datetime object in Python, convert the datetime to a date using date(). You can also use strftime() to create a string from a datetime object without the time. When working in Python, many times we need to create variables which represent dates and times.
d1.date() == d2.date()
From the Python doc:
datetime.date()
Return date object with same year, month and day.
Cast your datetime object into a date object first. Once they are of the same type, the comparison will make sense.
if d2.date() == d1.date():
print "same date"
else:
print "different date"
For your case above:-
In [29]: d2
Out[29]: datetime.date(2012, 1, 19)
In [30]: d1
Out[30]: datetime.datetime(2012, 1, 19, 0, 0)
So,
In [31]: print d2 == d1.date()
True
All you needed for your case was to make sure you are executing the date method with the brackets ()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With