3

I have a layer in QGIS that has four date fields - date1, date2, date3, date4. Using pyqgis I wish to find the latest date (ignoring null values) for every record from these four columns and copy that value into a field called MaxDate.

If the four date fields are null, then MaxDate is set at the value of last_date

It feels like there should be an easy solution, but I have yet to crack it!

The fields are all 'QDate' format (yyyy-MM-dd)

Data Example

closed as off-topic by ahmadhanb, BERA, whyzar, aldo_tapia, tinlyx Mar 21 '18 at 17:14

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions seeking help to debug/write/improve code must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Providing a clear problem statement and evidence of a code attempt will help others to help you. See: How to create a Minimal, Complete, and Verifiable example." – ahmadhanb, BERA, whyzar, aldo_tapia, tinlyx
If this question can be reworded to fit the rules in the help center, please edit the question.

4

Here is a PyQGIS solution. It assumes that you have already all the fields created with the same names you mentioned above:

layer = iface.activeLayer()

for feat in layer.getFeatures():
    featureList=[feat['date1'], feat['date2'], feat['date3'], feat['date4']]
    idx = layer.fieldNameIndex( 'maxDate' )
    layer.startEditing()

    try:
        maxDate=max(x for x in featureList if x !=qgis.core.NULL)
        feat[idx]=maxDate
        layer.updateFeature(feat)
        layer.commitChanges()
    except ValueError:
        feat[idx]=feat['last_date']
        layer.updateFeature(feat)
        layer.commitChanges()

print 'Done'

EDIT: Code adjusted to ignore null values, taking instead highest date found. If all the dates are null, then the value from 'list_date' is returned.

Example with sample data:

enter image description here

  • Thanks 15Step, that works perfectly! Its working out the iteration steps that had me stumped. – Tom Mar 21 '18 at 14:34
  • Great! :) It would be nice if you could accept my answer (the green arrow) – 15Step Mar 21 '18 at 14:48
  • 1
    sorry - forgot that bit! Done – Tom Mar 21 '18 at 14:54

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