QGIS – How to Update Attribute Table in Multiple Layers Using Field Calculator

attribute-tablefield-calculatorpyqgisqgis

I have dozens of layers in QGIS and all these layers have attribute field that I would like to update. I don't want to create new temporal layers with updated fields, rather just update the current layer attribute tables. And I wouldn't want to separately update each layer. I tried field calculator but it creates a new temporal layer. Is there any other solutions that could work? I'm using QGIS 3.22.

enter image description here

Best Answer

You can use pyqgis with re (to find the date) and datetime (to format the date) modules.

The layers must have a 8 digit date somewhere in the layername, formatted like 20211221 (YYYYMMDD). Try it on a subset of layers and backup your data first.

import re, datetime
fieldname = 'modified' #A string field that must exist in each table, change to match your fieldname

patt = r'\d{8}' #Search layername for 8 consecutive digits
for layer in QgsProject.instance().mapLayers().values(): #For each layer added to QGIS
    attrMap = {} #A dictionary to hold feature id: fieldindex:new value
    found = re.search(patt, layer.name()) #Find the 8 digits in a row
    fieldindex = layer.fields().indexFromName(fieldname) #Find the index of "modified" field
    if found:
        oldval = datetime.datetime.strptime(found.group(), '%Y%m%d') #datetime.datetime(2021, 11, 12, 0, 0) #Create a datetime object
        newval = datetime.datetime.strftime(oldval, '%m%d%Y') #Convert to a string in the format you want
        for f in layer.getFeatures():
            attrMap[f.id()] = {fieldindex:newval}
        layer.dataProvider().changeAttributeValues(attrMap)

enter image description here

Related Question