Datetime comparison using f strings in python

Viewed 69

Consider the following dataframe

Y = pd.DataFrame([("2021-10-11","john"),("2021-10-12","wick")],columns = ['Date','Name'])
Y['Date'] = pd.to_datetime(Y['Date'])

Now consider the following code snippet in which I try to print slices of the dataframe filtered on the column "Date". However, it prints a empty dataframe

for date in set(Y['Date']):
    print(Y.query(f'Date == {date.date()}'))

Essentially, I wanted to filter the dataframe on the column "Date" and do some processing on that in the loop. How do I achieve that?

2 Answers

Use "" because f-strings removed original "" and error is raised:

Y = pd.DataFrame([("2021-10-11","john"),("2021-10-12","wick")],columns = ['Date','Name'])

Y['Date'] = pd.to_datetime(Y['Date'])


for date in set(Y['Date']):
    print(Y.query(f'Date == "{date}"'))

The date needs to be accessed at the following query command:

Y = pd.DataFrame([("2021-10-11","john"),("2021-10-12","wick")],columns = ['Date','Name'])
for date in set(Y['Date']):
    print(Y.query('Date == @date'))
Related