Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I compare a date and a datetime in Python?

Tags:

python

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.)

like image 775
Mridang Agarwalla Avatar asked Jul 19 '10 06:07

Mridang Agarwalla


People also ask

Can we compare two timestamps in Python?

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.

How do you check if a date is before another date in Python?

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.

How do you compare two dated?

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.


2 Answers

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.

like image 88
kennytm Avatar answered Oct 10 '22 01:10

kennytm


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 
like image 37
samarth Avatar answered Oct 10 '22 03:10

samarth