Wednesday, 13 December 2017

Making automatic updated date and time field in QGIS?


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 bellow.


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 it self.

  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.



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.



No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...