Removing the time zone from datetime field in QGIS
datetimefields-attributesqgisqgsexpressiontime zone
How can I get rid of the time zone in the date/time field?
So I have a GeoPackage with the following data:
and want to get just 2021-06-07 16:25:40
Best Answer
In my QGIS (3.22), when I use datetime format, I get timezone information included by default. You can convert it to a string to get rid of it - use this expression, where datetime is the name of the field containing the datetime-information:
left(to_string(datetime), 19)
However, you can't use the resulting string field as a datetime field any more. Including timezone makes sense - as 2021-12-06 14:48:41 is not the same everywhere on Earth.
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:
Note: I used a string field instead of date in order to get the time, otherwise the date field only records YYYY-MM-DD.
Best Answer
In my QGIS (3.22), when I use
datetime
format, I get timezone information included by default. You can convert it to a string to get rid of it - use this expression, wheredatetime
is the name of the field containing the datetime-information:However, you can't use the resulting string field as a
datetime
field any more. Including timezone makes sense - as2021-12-06 14:48:41
is not the same everywhere on Earth.