TransWikia.com

Obtaining date data from layer name in QGIS

Geographic Information Systems Asked by Newton Monteiro on November 28, 2020

I have a column with name of the satellites image background (Landsat, Sentinel), in this name I have a date information into the text.

How do I extract the date data from this text?

2 Answers

Tested on QGIS 3.4

Case 1. if there is a column in attribute table with names of TIFF-files

regexp_substr('LC13_L1TP_PPPRRR_20191011_20191013_CC_TX','([12]\d{3}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01]))')

output: '20191011'


Case 2. if TIFF-files were loaded as separate Raster layers

Let's assume there two TIFF-files which names match the Landsat Product Identifier, i.e. LXSS_LLLL_PPPRRR_YYYYMMDD_yyyymmdd_CC_TX and some other layers, see image below.

input

Based on the description, the targeting date is defined by YYYYMMDD (Acquisition Date expressed in Year, Month, Day).

Paste the following code in Plugins > Python Console > Show editor > New Editor. It will facilitate obtaining a list with date data from uploaded TIFF-files.

from datetime import datetime
import re

mapcanvas = iface.mapCanvas()
n = mapcanvas.layerCount()
layers = [mapcanvas.layer(i) for i in range(n)]

layers_names = []

for layer in layers:
    if layer.type() == QgsMapLayer.RasterLayer:
        layers_names.append(layer.name())
    else:
        continue

layers_names_dates = []
pattern = re.compile(r'd{4}d{2}d{2}')

for i, element in enumerate(layers_names):
    result = re.search(pattern, element)
    if result:
        result = result.group()
        val = datetime.strptime(result,'%Y%m%d').strftime('%d%m%Y')
        layers_names_dates.append(val)
    else:
        continue

print(layers_names_dates)

Note: that re.search only checks for the first match in the string.

The output might be looking as follows

>>> exec(open('C:/Users/TARAS~1/AppData/Local/Temp/tmp5ep5qejq.py'.encode('utf-8')).read())
['11092019', '10092019']

References:

Answered by Taras on November 28, 2020

Create a calculated virtual field, using the string functions of QGIS.

For example, Landsat filenames have the following format:

LXSS_LLLL_PPPRRR_YYYYMMDD_yyyymmdd_CC_TX

The acquisition date part is YYYYMMDD, hence you want to extract the characters between 18 and 25, inclusive. To do so, define a new virtual text field called for example acq_date with the following expression:

substr("filename",18,25)

Where "filename" is the name of the field containing the name of the Landsat imagery file.

For other filename standards, you will need to adjust the from and to values (in my example, 18 and 25 respectively) to the actual file name you are handling.

Answered by RafDouglas on November 28, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP