Search code examples
apigoogle-analyticsanalyticsgoogle-analytics-api

How to filter by dateHour on Google Analytics API?


I'm trying to retrieve results from the Google Analytics API that are between two specific dateHours. I tried to use the following filter:

'filters' => 'ga:dateHour>2013120101;ga:dateHour<2013120501'

But this doesn't work. What do I need to do? (I've used other filters before, and they work just fine).


Solution

  • First off, you're trying to use greater than and less than on a dimension which doesn't work. Dimension filters only allow ==, !=, =@, !@,=~, and !=.

    So, if you want to get ga:dateHour, you'll have to use a regex filter:

    ga:dateHour=~^2013120([1-4][0-2][0-9]|500)$;ga:dateHour!~^201312010[0-1]$
    

    EDIT: I wouldn't hesitate a second to learn RegEx, especially if you're a programmer. Here is a great SO post on learning regular expressions.

    So, to break it down:

    =~ looking to match the following regex
    != not looking to match the following regex 
    

    (check out GA's filter operators)

    ^ at the start of a string

    2013120 since the entire dateHour range contained this string of numbers, look for that

    ([1-4][0-2][0-9]|500) match every number after 2013120, so the first [1-4] will match 20131201, 20131202, 20131203, and 20131204, then within those strings we want the next number to be [0-2] and likewise with [0-9]. So look at each [ ] as a placeholder for a range of digits.

    | means or

    500 says, we only want 500 and nothing more, so it's very specific.

    The whole statement is wrapped in () so we can say he, match [1-4][0-2][0-9] OR 500, after 2013120.

    Then, we end it with $ to signify the end of the string.

    This probably isn't the most concise way to describe how this filter is working, but what I would do is use a website like regexpal or some other regex testing tool, and get the range you'd like to filter and start writing regex.

    Best of luck!