# Finding the index of certain strings in a list

I'm actually using a dataset of much greater dimensions and length but I simplified my problem of string patterns in order to ask this question.

dates = {"2018-01-01 22:00:00", "2018-01-01 22:30:00", "2018-01-01 23:00:00", "2018-01-01 23:30:00", "2018-01-02 00:00:00", "2018-01-02 00:30:00",
"2018-01-02 01:00:00", "2018-01-02 01:30:00", "2018-01-02 02:00:00", "2018-01-02 02:30:00", "2018-01-02 03:00:00", "2018-01-02 03:30:00",
"2018-01-02 04:00:00", "2018-01-02 04:30:00", "2018-01-02 05:00:00", "2018-01-02 05:30:00", "2018-01-02 06:00:00", "2018-01-02 06:30:00",
"2018-01-02 07:00:00", "2018-01-02 07:30:00", "2018-01-02 08:00:00", "2018-01-02 08:30:00", "2018-01-02 09:00:00", "2018-01-02 09:30:00",
"2018-01-02 10:00:00", "2018-01-02 10:30:00", "2018-01-02 11:00:00", "2018-01-02 11:30:00", "2018-01-02 12:00:00", "2018-01-02 12:30:00",
"2018-01-02 13:00:00", "2018-01-02 13:30:00", "2018-01-02 14:00:00", "2018-01-02 14:30:00", "2018-01-02 15:00:00", "2018-01-02 15:30:00",
"2018-01-02 16:00:00", "2018-01-02 16:30:00", "2018-01-02 17:00:00", "2018-01-02 17:30:00", "2018-01-02 18:00:00", "2018-01-02 18:30:00",
"2018-01-02 19:00:00", "2018-01-02 19:30:00", "2018-01-02 20:00:00", "2018-01-02 20:30:00", "2018-01-02 21:00:00", "2018-01-02 21:30:00",
"2018-01-02 22:00:00", "2018-01-02 22:30:00", "2018-01-02 23:00:00", "2018-01-02 23:30:00", "2018-01-03 00:00:00", "2018-01-03 00:30:00",
"2018-01-03 01:00:00", "2018-01-03 01:30:00"}


Assuming I have the above list of dates, I'm trying to find the index of the dates matching the below string pattern.

patt = ___ ~~ "23:30:00"


Both Positions nor Cases return empty with my pattern. StringCases does but the output is a bit unwieldily.

StringCases[dates, patt]


Which means I have to do something like below to get the indexes I need.

Select[
PositionIndex[
StringCases[ dates , patt ]
],
Length@# < 2 &
] // Values // Flatten

(* Returns *)
{4, 52}


Does anyone know of a way to directly get the index of a string pattern with Position?

Pick[Range @ Length @ dates, StringMatchQ[patt] @ dates]


{4, 52}

Pick[Range @ Length @ dates, StringEndsQ["23:30:00"] @ dates]


{4, 52}

Flatten @ Position[_String?(StringMatchQ[patt])] @ dates

{4, 52}

Flatten @ Position[_String?(StringEndsQ["23:30:00"])] @ dates

{4, 52}

patt = __ ~~ "23:30:00"
pos1 = Position[dates, x_String /; StringMatchQ[x, patt]]


{{4}, {52}}

To extract these values:

Extract[dates, pos1]


Since dates and times are involved, try the following:

Position[dates, x_String /; TimeObject[x] == TimeObject["23:30:00"]]

Position[StringMatchQ[dates, ___ ~~ "23:30:00"], True]


Flatten it if you want literally just a list of integers.

p = Position[Last @* StringSplit /@ dates, "23:30:00"]


{{4}, {52}}

Extract[dates, p]


{"2018-01-01 23:30:00", "2018-01-02 23:30:00"}