At QGIS 3.28.6 I have an attribute table containing a datetime field from which I need to populate an integer field that will contain the day of year (for example, 2/1/2018 would output to 32).

Using the Field Calculator, when I enter the expression day("datetime_field") the answer is the day of the month (here, 2/1/2018 outputs to the value of 1, instead of the desired 32).

Interestingly, the expression week("datetime_field") returns the week of the year, e.g. 1-52. I need the same, only for day of the year.

A search through GIS SE, as well as an internet search, came up empty.

How to calculate day of the year from a datetime field?

1 Answer 1


Use this expression, based on function age(). The idea is the calculate the difference in days between your date and Jan 1 of that year.

The first argument is your date, and the second argument is the first day of the year: January 1, created as string, combined (concatenated with pipes operator ||) with the year of your date, calculated with the year() function:

day (age (date, to_date (year (date) || '-01-01'))) + 1

Calculating the day of the year for the 1st of each month + Dec. 31 results in different values for 2018 and 2020 (leap year, values from March on), as expected: enter image description here

  • Very good! I might add one edit: the Field Editor requires that the date field (red text in your answer) needs to be surrounded by double quotes.
    – Stu Smith
    Commented May 23, 2023 at 3:07
  • 1
    Double quotes are optional, but probably it's indeed better/good style to use them
    – Babel
    Commented May 23, 2023 at 4:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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