Making automatic updated date and time field in QGIS?

You can use the following code which connects the attributeValueChanged event to a function we can define which inserts the results of the $now expression. Highlight your layer and copy/paste the following into the Python Console:

layer = qgis.utils.iface.activeLayer()

def update():
    field = layer.fieldNameIndex('mod')
    e = QgsExpression( " $now " )
    e.prepare( layer.pendingFields() )
    for feat in layer.selectedFeatures():
        feat[field] = e.evaluate( feat )
        layer.updateFeature( feat )

layer.attributeValueChanged.connect(update)

Select the feature by clicking the row number (shown in the red box in the image) or from the map canvas and edit any attribute for that feature. The attribute in your mod field should update:

Result


Note: I used a string field instead of date in order to get the time, otherwise the date field only records YYYY-MM-DD.


I stumbled upon this Q&A while I was looking for a way to date/time stamp changes I was making to records using a plugin. I placed a slightly modified version of the code into the plugin to automatically update the date/time into the record(s) I changed:

""" Prepare Change Date/Time Stamp"""
e = QgsExpression( " $now " )
cDate = e.evaluate()

"""" Identify column(s) to change and new value(s) to assign"""
attrs = { 10 : newStat, 20 : cDate }

""" Make record change and capture date/time of change'''
layer.dataProvider().changeAttributeValues({ fid : attrs })