I have a CSV in QGIS and one of the columns is "Data/Hora GPS" with the DateTime in format (day/month/year hour:minute:second), in the field calculator I used the expression for filter:

to_datetime("Data/Hora GPS",'dd/MM/yyyy HH:mm:ss') >
  to_datetime('03/02/2010 14:20:00', 'dd/MM/yyyy HH:mm:ss') and
  to_datetime("Data/Hora GPS",'dd/MM/yyyy HH:mm:ss') <
  to_datetime('04/02/2010 15:00:00', 'dd/MM/yyyy HH:mm:ss')

But now I want to do this in PyQGIS, How I can do that? (The Data/Hora GPS is a string column)


1 Answer 1


You can set the filter manually to make sure the syntax is correct. Maybe you should use your locales date format, mine is YYYY-MM-DD HH:MM:SS


"Data/Hora GPS" > '1992-03-05 14:20:00' AND "Data/Hora GPS" < '1992-03-20 15:00:00'

then execute the rows

layer = QgsProject.instance().mapLayersByName("randomdates")[0] #Change to the name of your layer
"Data/Hora GPS" > '1992-03-05 14:20:00' AND "Data/Hora GPS" < '1992-03-20 15:00:00'

To see what the filter string looks like.

Then apply the filter:

layer.setSubsetString('') #Clear the filter
filterstring = "\"Data/Hora GPS\" > '1992-03-05 14:20:00' AND \"Data/Hora GPS\" < '1992-03-20 15:00:00'" #You need to escape \" the inner double quotes

  • Thanks, it really worked, but I think the filter is reading the date conditions as a string, is that ok? Doesn't this mean that under certain date conditions it ends up not filtering exactly to the date I want because it's being read as a string? I don't know much about programming
    – Mestrexama
    Jul 1, 2023 at 19:58
  • I believe it is the correct syntax for dates and it should work.
    – BERA
    Jul 2, 2023 at 7:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.