QGIS – Splitting String with Dates and Extracting Earliest and Latest Dates

dateformatpyqgisqgisstring

I have dates separated by '/' character in column "date" in format RRMMDD as on the screenshot below:

input_qgis

I want to separate dates into another columns "date_from", "date_to" and convert dates into YY.MM.DD format by adding dots as on following picture

output_qgis

In QGIS, there is any formula to separate values between '/' character and export MIN/MAX values into another columns?

Best Answer

You can use PyQGIS:

from datetime import datetime as dt

lyr = QgsProject.instance().mapLayersByName('New scratch layer')[0]
fieldnames = ['date', 'date_from', 'date_to']

indices = [lyr.fields().indexFromName(fn) for fn in fieldnames[1:]] #Find indices for the fields to update
attrmap = {} #A dictionary to hold the new values
for f in lyr.getFeatures():
    dates = f[fieldnames[0]].split('/') #Split date string into a list of strings
    dates = [dt.strptime(x, '%y%m%d') for x in dates] #Convert strings to dates
    fromdate, todate = [dt.strftime(x, '%y.%m.%d') for x in [min(dates), max(dates)]] #Extract min and max date and convert back to strings with dots between year month and day
    attrmap[f.id()] = {indices[0]:fromdate, indices[1]:todate} #Store in the dictionary
    
lyr.dataProvider().changeAttributeValues(attrmap) #Update values

enter image description here

Related Question