Formatting datetime object in df.query(), Python

‘I would like to format a datetime object within df.query(). The following command works for me

df.query(''''2001-01-01'<eventdate''')

where eventdate is a multi index column in df. However, I cannot get the following to work

m='2001-01-01'
df.query(f'''{m}<eventdate''')

which reads the error invalid syntax. I have tried the following with no luck.

ts=pd.Timestamp
m='2001-01-01'
df.query(f'''@ts({m})<eventdate''')

Any suggestions would be really appreeciated. Thank you.

>Solution :

If you want it with quotation marks around the date inside the query string, use this:

    m="'2001-01-01'"
    df.query('''{}<eventdate'''.format(m))

Leave a Reply