Skip to content

Instantly share code, notes, and snippets.

@sickel
Last active February 23, 2025 14:17
Show Gist options
  • Save sickel/97c2330550d34c1938b3038d5d37d86e to your computer and use it in GitHub Desktop.
Save sickel/97c2330550d34c1938b3038d5d37d86e to your computer and use it in GitHub Desktop.
A script to make fields with year, day of year and decimal hour from a epoch field in QGIS
# From a layer with a timestamp as an epoch number,
# adds in fields for year, day of year and decimal hour if they do not exist yet
# goes through the dataset, calculate the year, doy and hour and populates the fields
import datetime
epochfield = 'acqtime'
layer = qgis.utils.iface.activeLayer()
if layer.dataProvider().fieldNameIndex(epochfield) == -1:
# Do not want to do anything on a layer without an epoch field
print(f'Data layer does not have an "{epochfield}" field')
else:
stopEditing = False
if not layer.isEditable():
stopEditing = True
layer.startEditing()
if layer.dataProvider().fieldNameIndex("year") == -1:
layer.dataProvider().addAttributes([QgsField("year", QVariant.Int)])
if layer.dataProvider().fieldNameIndex("doy") == -1:
layer.dataProvider().addAttributes([QgsField("doy", QVariant.Int)])
if layer.dataProvider().fieldNameIndex("hour") == -1:
layer.dataProvider().addAttributes([QgsField("hour", QVariant.Double)])
layer.updateFields()
for feature in layer.getFeatures():
epoch = feature[epochfield]
epoch = int(epoch)
rectime = datetime.datetime.fromtimestamp(epoch)
year = rectime.strftime('%Y')
feature['year'] = int(year)
doy = rectime.strftime('%j')
feature['doy'] = int(doy)
hour = rectime.strftime('%H')
minute = rectime.strftime('%M')
second = rectime.strftime('%S')
dechour = int(hour)+int(minute)/60 + float(second)/3600
feature['hour'] = dechour
layer.updateFeature(feature)
layer.commitChanges(stopEditing)
# stopEditing signals if the editing should or should not be active
# after the commit

Comments are disabled for this gist.