In QGIS python console, I can run the following to extract the week number from date column. How can I use the same in qgsExpression as a where clause? Any other option is welcome as long as it uses PyQGIS. I intend to filter a vector layer in QGIS to return records that match a particular week.
for x in layers:
if x.name() == "test":
idx = x.fieldNameIndex("date_from")
values = x.uniqueValues( idx )
b =values[0]
print b.weekNumber()
b.weekNumber()[0]
This expression gives me an indication of the week number. Can I use QgsExpression like
expr = QgsExpression( "\"date_from.weekNumber()\" = 99" )
?
1 Answer 1
You could use the following as a QgsExpression
to check if a week number is, for example, 39:
expr = QgsExpression( ' week("date_from") = 39 ' )
Just as an example, the following code uses the above expression to find features which have a week number of 39. If one does then it's row number will be printed which could then be used for filtering:
layers = QgsMapLayerRegistry.instance().mapLayers().values()
for x in layers:
if x.name() == "test":
idx = x.fieldNameIndex("date_from")
values = x.uniqueValues( idx )
expr = QgsExpression( ' week("date_from") = 39 ' ) # Set week number to 39
for f in x.getFeatures():
f[idx] = expr.evaluate( f )
if f[idx] == 1: # Uses Boolean values (0 = False; 1 = True)
print "row number: ", f.id()
Note: The date_from
field I used was a Date-type field, so the format was YYYY-MM-DD.
Hope this helps!