QGIS – Making an Automatically Updated Date and Time Field

datedatetimefield-calculatorqgisupdate

I want to make a date and time updated field as I edit an attribute field in this format yyyy-mm-dd 00:00:00 (= 2016-05-08 11:04:00) – my local date/time. The data is in a QGIS 2.14 shapefile and vector lines as screenshot below.

When a feature as NULL in the 'name' field, I want to enter a name for the road and the 'mod' field must receive de modified date/time like '2016-05-08 15:16:00'.

I already tried some options and failed.
I need help to start from beginning.

  1. I create a new field, date/time type, but stays with NULL value after I edited, in the "name" field, or the feature itself.
  2. I used too, the expression now(), but stays with NULL value after I edited.

Note: the date seen there, 2016-04-14 is the first value created with "Field Calculator".

enter image description here

I am using QGIS 2.14.

Best Answer

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.

Related Question