Here's a little snippet that I'm trying execute:
>>> from datetime import * >>> item_date = datetime.strptime('7/16/10', "%m/%d/%y") >>> from_date = date.today()-timedelta(days=3) >>> print type(item_date) <type 'datetime.datetime'> >>> print type(from_date) <type 'datetime.date'> >>> if item_date > from_date: ... print 'item is newer' ... Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can't compare datetime.datetime to datetime.date
I can't seem to compare the date and the datetime values. What would be the best way to compare these? Should I convert the datetime to date or vice-versa? How do i convert between them.
(A small question but it seems to be a little confusing.)
And, it is required to compare timestamps to know the latest entry, entries between two timestamps, the oldest entry, etc. for various tasks. Comparison between pandas timestamp objects is carried out using simple comparison operators: >, <,==,< = , >=. The difference can be calculated using a simple '–' operator.
Check if One DateTime is Less than other DateTime You can use less than comparison operator < to check if one datetime object is less than other.
In Java, two dates can be compared using the compareTo() method of Comparable interface. This method returns '0' if both the dates are equal, it returns a value "greater than 0" if date1 is after date2 and it returns a value "less than 0" if date1 is before date2.
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
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