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?
Best Answer
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 theyear()
function: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: