Date and time regexs

Sometimes you just want to grab a period of event information from a logfile, or similar.

I should probably turn this into a regex generator of some description, but, in the meantime, here are some examples of how you can grep out time ranges from ISO 8601 timestamped entries e.g. 2018-11-04T11:34:05Z

Note: I’m sure some will point out that the ‘correct’ solution to this problem is to convert the strings to datetime objects and then select from linear ranges; this is not that solution.

Specific day

grep -E '2018\-11\-04'

Note: the escaped hyphen separator

Specific hour

grep -E '2018\-11\-04T11'

Spanning hours

Include 11:00 and 12:00

grep -E '2018\-11\-04T1[1-2]'

Range of minutes (simple)

11:03-11:06 inclusive

grep -E '2018\-11\-04T11\:0[3-6]'

Range of minutes (less simple)

11:34-11:44; we have to deal with the range as an option as it spans the 10’s of minutes boundary

grep -E '2018\-11\-04T11\:(3[4-9]|4[0-4])'

Range of minutes (complex)

11:55-12:05; a more complex range including minutes and hours

grep -E '2018\-11\-04T(11\:5[5-9]|12\:[0-5])'

Note: we could also write this as:

grep -E '2018\-11\-04T1(1\:5[5-9]|2\:[0-5])'

but I think the first form is more clear in its intent – never a bad thing with regexes!

 

 

 

Leave a comment