[GIS] How to calculate with time values in QGIS

field-calculatorqgisqttime

I have two string fields in a vector layer, "From" and "To", with values in the format of 10:16:30 and 10:18:00 e.g.

I would like to calculate the difference in minutes as a decimal value, in this case 1.5, in the field calculator and write it to a real field for further calculations.

As I understood so far, I have to convert my strings to QT time type by using totime("From") and totime("To").

But now I already reached the end of my wisdom. No matter what I try, the field calculator doesn't accept any further combination of other functions (Expression is invalid).

Can anyone please tell me how to perform this calculation and receive a real field with a real minutes value, or can point me to some resources with working examples?

Best Answer

It's possible without using a python function, with a little bit of hacks:

minute( age( todatetime('2000-01-01 10:18:00'), todatetime(2000-01-01 10:16:30') ) )

will return "1.5".

To break it down, "age" returns the difference between two datetimes as an interval type. This needs to be wrapped in the "minute" function to extract the length of this interval in minutes. Lastly, I've had to put dummy dates into the "todatetime" functions as the "age" function only operates on datetime types, not plain times.