5

I have a layer with datetime field with milliseconds. I use the following script to get a QDateTime object and add it to a memory layer:

layer = QgsVectorLayer("Point?crs=EPSG:4326", "test", "memory")
layer.dataProvider().addAttributes([QgsField("dt", QVariant.DateTime)])
layer.updateFields()
QgsProject.instance().addMapLayer(layer, True)

s = "22/04/20 05:14:38:560"
dt = QDateTime.fromString(s[:-3], "yy/MM/dd HH:mm:ss:zzz").addYears(100)

feat = QgsFeature(layer.fields())
feat.setGeometry(QgsGeometry()) # empty geometry for test
feat["dt"] = dt

layer.dataProvider().addFeatures([feat])
layer.updateExtents()

enter image description here

As in the image, although the millisecond part is missing in the attribute table, I can get whole datetime value including milliseconds as follows:

feat = list(iface.activeLayer().getFeatures())[0]
print(feat["dt"])

#                                                     vvv millisecond
# OUT: PyQt5.QtCore.QDateTime(2022, 4, 20, 5, 14, 38, 560)

But when I export the layer as CSV or Excel file using "Export > Save Features As...", it doesn't add the milliseconds part to the file:

dt,
2022/04/20 05:14:38

How can I export the layer to include the milliseconds part?

0

1 Answer 1

4

If you register a custom formatter as described in my answer on your related question (Displaying milliseconds in Attribute Table using PyQGIS), the formatter can be applied to modify the exported datetime values.

In the Export > Save Features As... menu, tick the option Use Date/Time within the Replace with displayed values column. QGIS then exports all datetime values exactly as shown in the Attribute Table, therefore including the desired milliseconds part.

check_option

Resulting in the following file content after export:

dt,
20/04/2022 05:14:38:560

Not the answer you're looking for? Browse other questions tagged or ask your own question.