2

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" )?

Joseph
76.7k8 gold badges173 silver badges286 bronze badges
asked Sep 23, 2015 at 8:00

1 Answer 1

2

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!

answered Sep 23, 2015 at 11:55
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.