Comparing datetime objects by date only

Question:

I have two datetime objects having same day, month and year, say:

test_date = datetime.datetime(2014, 4, 25, 11, 57, 56)

(above date is created like datetime.utcfromtimestamp(utc_timestamp)) and

now_date  = datetime.datetime(2014, 4, 25, 12, 40, 19, 705355)

(above date is created like datetime.now()). When I say

now_date==test_date

I get False when it should be True. How can I compare correctly?

Asked By: navyad

||

Answers:

If you just want to compare day, month and year, you may just try:

now_date.strftime('%Y%m%d')==test_date.strftime('%Y%m%d')

Using this method, you can also specify other attributes.

Answered By: yejinxin

You are currently comparing the whole datetime object, including the time (which doesn’t match). Instead, just compare the date part:

>>> now_date.date() == test_date.date()
True
Answered By: jonrsharpe

Since, you just want to compare the dates and not the time, you need to convert these to datetime.date objects which strip out the time related information.

In [1]: import datetime

In [2]: test_date = datetime.datetime(2014, 4, 25, 11, 57, 56)

In [3]: now_date = datetime.datetime(2014, 4, 25, 12, 40, 19, 705355)

In [4]: now_date == test_date
Out[4]: False

In [5]: test_date = test_date.date()

In [6]: test_date
Out[6]: datetime.date(2014, 4, 25)

In [7]: now_date = now_date.date()

In [8]: now_date
Out[8]: datetime.date(2014, 4, 25)

In [9]: now_date == test_date
Out[9]: True
Answered By: Aditya

Simple function

def date_extracter(string):
    day = re.search('d{4}-d{2}-d{2}', string)
    date = datetime.datetime.strptime(day.group(), '%Y-%m-%d').date()
    return date
Answered By: FrontendDev
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.