For some expression in QGIS I need to get the number of days between two dates as numeric value.

If I substract two dates I get an interval back:

to_date('2019-12-31') - to_date('2019-01-01')


<interval: 364 days>

I get the same return type from the age() function.

Is there a straightforward approach to get the number of days as numeric value?

I am not looking for solutions that involve converting to epoch and doing my own math nor for solutions that rely on string parsing. I am looking for an built-in approach that I might be overlooking.

  • 3
    see > nathanw.net/2012/06/30/… – Mapperz Aug 19 '19 at 13:52
  • 1
    Nice! I did not expect the day() function to work on intervals due to its name. Thanks! Do you want to add it as answer? Otherwise I will do so. – bugmenot123 Aug 19 '19 at 14:08
  • Done! Thanks again. – bugmenot123 Aug 20 '19 at 8:05
  • I cannot get the following to work: exp = QgsExpression(to_date(mostRecent) - to_date(secondNewest)) Produces: "NameError: name 'to_date' is not defined" What am I doing wrong? – grego Aug 11 at 23:43
  • 1
    I never used QgsExpression but I guess you need to pass a string with the expression in it to it. This is better asked in a new question. – bugmenot123 Aug 12 at 9:23

The functions to extract temporal "parts" year(), month(), week(), day(), hour(), minute() and second() have a secondary function on intervals where they actually calculate the number of years, months, weeks and so on.

For example

  to_date('2019-12-31') - to_date('2019-01-01')



as there are that many days in that time interval.

Thanks to @Mapperz for the link.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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