2

Say I have a bunch of time stamps

As I iterate over these timestamps,

01:23:00 12:34:14 17:09:12 ... 

I want to include only timestamps between 08:00:00 and 17:00:00

please suggest

5
  • @Andrei - presume those are hours:minutes:seconds - is that time window fixed, e.g. might you ever need a time window that crosses midnight? Commented May 25, 2010 at 13:55
  • possible duplicate of compare time using date command Commented May 25, 2010 at 13:55
  • The only difference between this and your previous question is that now you say you're looping over some input. If you need help looping, ask about that. If you need more help with date/time comparison, edit or comment on your previous question. Commented May 25, 2010 at 13:56
  • yes, it is not duplicate as I am not using the current timestamp Commented May 25, 2010 at 14:15
  • @Andrei: I added that answer to the other question. It's a trivial extension of what was already there. Commented May 25, 2010 at 14:17

1 Answer 1

8

You can do a simple string comparison:

if [[ "$timestamp" > "08:00:00" && "$timestamp" < "17:00:00" ]] 

If you want to include the ends of your range, you'll have to test for that separately since Bash doesn't have a >= or <= operators for strings:

start="08:00:00" end="17:00:00" if [[ "$timestamp" == "$start" || "$timestamp" > "$start" && "$timestamp" < "$end" || "$timestamp" == "$end" ]] 
Sign up to request clarification or add additional context in comments.

2 Comments

I didn't know we could compare timestamps like this ... +1 Any possible pitfalls you see with this?
@JS웃: The example I show uses lexical comparisons and the OP's examples are all lexically sortable, so no I don't see any pitfalls under these conditions. You can even do it with full ISO 8601 (or similar) dates. If you're using Unix epoch timestamps, just use a numeric comparison if ((epoch_1 >= epoch_2))

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.