Question

I am working with a few slightly different styles of python datetimes. Problem is, I'd like to be able to equate them and I can't. From the database, I am getting datetimes in the format of:

datetime.date(2010, 11, 15)

Which, when returned, outputs:

2010-11-15

However, on my end, I need to turn some dates in a csv file into a date time. I do so by using the datetime.datetime.strptime package. So, here my code looks like this:

date = '11/15/2010' #The format in the CSV file
date = date.replace('/', ' ')
date2 = datetime.datetime.strptime(date, '%m %d %Y')

However, date2, when printed, outputs:

2010-11-15 00:00:00

And the two dates, though actually equivalent, won't evaluate to True when I throw a == in between them. Is there a way to use datetime.datetime.strptime to leave out hours, minutes, seconds? I'd like to conform to the format used in the first example (my database). Thanks

Was it helpful?

Solution

You're trying to compare a datetime and a date. To compare them, simply do:

date2.date() == datetime.date(2010,11,15)

and you should be fine.

A bit more context:

In [1]: import datetime

In [2]: datetime.date.today()
Out[2]: datetime.date(2013, 10, 28)

In [3]: datetime.datetime.now()
Out[3]: datetime.datetime(2013, 10, 28, 11, 5, 43, 997651)

In [4]: datetime.datetime.now() == datetime.date.today()
Out[4]: False

In [5]: datetime.datetime.now().date() == datetime.date.today()
Out[5]: True
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top