Wesley van Straalen
Wesley van Straalen

Reputation: 45

Comparing current date in object with dates from database

I'm trying to check if the currentdate is inside a list with multiple records of my database. The records im getting back are not only dates but also other stuff. If i print the list i get the following as return

((0L, datetime.date(2018, 1, 29)), (0L, datetime.date(2018, 1, 30)), (1L, datetime.date(2018, 1, 31)))

The currentdate i state as followed

 currentdate = time.strftime("%Y/%m/%d")
 cd_dt = datetime.strptime(currentdate, '%Y/%m/%d').date()

Now i try to compare them like this:

print(cd_dt in result_set)

This returns false even though todays date is inside that list.

How would i fix this?

Thank you in advance

Upvotes: 0

Views: 35

Answers (2)

Jim Macaulay
Jim Macaulay

Reputation: 5155

List = ((0L, datetime.date(2018, 1, 29)), 
        (0L, datetime.date(2018, 1, 30)), 
        (1L, datetime.date(2018, 1, 31)))

currentdate = time.strftime("%Y/%m/%d")
cd_dt = datetime.strptime(currentdate, '%Y/%m/%d').date()

return cd_dt in List

Try above code. It works.

Upvotes: 0

Sohaib Farooqi
Sohaib Farooqi

Reputation: 5666

The problem with your code is you are trying to match time object with a tuple of tuple. If you want to fix your solution you can use the following line to fix:

Change

>>> print(cd_dt in result_set)

To

>>> any(d[1] == cd_dt for d in k)
>>> True

You can use builtin filter to filter the result set. In this way you can also get the matched element(s) of result set.

>>> import datetime
>>> k = ((0L, datetime.date(2018, 1, 29)), (0L, datetime.date(2018, 1, 30)), (1L, datetime.date(2018, 1, 31)))
>>> list(filter(lambda x: x[1] == datetime.date.today(),k))
>>> [(1L, datetime.date(2018, 1, 31))]

Or if you just want to check if the current date is in the result set you can use any

>>> any(d[1] == datetime.date.today() for d in k)
>>> True

Upvotes: 1

Related Questions