In today’s article I am going to share a solution on how to create an array of dates to loop through in an Azure Data Factory pipeline. An array like this can be useful when you need to run a set of activities for a specific date, and you need that period to be dynamic. For instance, in one pipeline run you wanted the last week, but in the next you need the whole month.
Aside from an Azure subscription and a Data Factory resource, the things needed are:
startDate
is the starting point of the period. The ForEach will start on this date and, depending on the timeDirection
parameter, will either add dates before or after this date. daysToGet
specifies the number of days to include in the array.
The way the rest of the logic in this demo pipeline is set up, timeDirection
can be a hyphen (-) to signify that we want dates before startdate
, or any other character to get dates after instead. Note startDate
is written in UTC format to simplify the code later on. The array is actually an array of UTC timestamps, but we are only interested in the date portions.
As an example, with the default values I included in the previous screenshot the pipeline would have an array with the week (last seven days) before March 1st 2021.
And here is the array variable, that defaults to an empty array:
This one-activity demo pipeline uses a ForEach to append each day to the array but, in a real pipeline, you would follow this up with a second ForEach to loop through that array and actually use the dates.
_This “Create date range” activity is looping through the values from zero until _daysToGet
so the array has the number of dates needed.
Inside the loop there is a single Append variable activity. This activity is enough to process the logic to get a date and append it to the array:
We have a couple of nested function calls to make sure we move as many days forward or backward as needed in each iteration of the loop. This piece of code does three things (starting from the if
):
startDate
or 1 if we want to move forward, by checking if the timeDirection
‘s value is a hyphen;if
(e.g. in the first iteration with an hyphen for timeDirection
, this multiplication would be 0 times -1, the second 1 times -1 and so on);startdate
as the result of the multiplication, thanks to the addDays
function. Again, with a timeDirection
poiting to the past, the first iteration of the loop would have a multiplication result of 0, so the startDate
is appended to the array, the second iteration appends the previous day (startDate
minus one day), the third iteration append the day before that, and so on.#data-science #azure-data-factory #azure