1

Here I have two timings start_time, end_time and interval and my output should be something like

Input:

  • start_time: 10:00 AM
  • end_time: 6:00 PM
  • interval: 10 min

my output should be as follows

10:00 AM
10:10 AM
10:20 AM
....
5:50 PM
6:00 PM

using postgres queries

1 Answer 1

4

You can use generate_series() for that. Unfortunately it does not support generating a series of time values directly. So you need to generate a series of "number of minutes" you want to add. In order to do that, you need to calculate the number of minutes between the start and end time and use that for generate_series()

select time '10:00' + interval '1' minute * gs.minutes 
from generate_series(0, 
                     (extract(epoch from time '18:00' - time '10:00') / 60)::int,
                     10) as gs(minutes);

The expression extract(epoch from time '18:00' - time '10:00') / 60 calculates the number of minutes between the start and the end time and passes that as the upper limit of values to generate (it needs to be cast to an integer to make generate_series() happy). The third parameter 10 specifies to generate number in increments of 10. This is then multiplied with an interval of 1 minute length and added to the start value.

Note that time literals written like that use the standard ISO 24 hour notation, not the AM/PM notation. But you can format your output using to_char() to get that if you want. But you should better format that in your application, not in SQL.

Online example: https://rextester.com/XUJ25540


An alternative way is to use the version of generate_series() that generates timestamps and cast the result to a time value (discarding the date part):

select gs.ts::time
from generate_series(current_date + time '10:00', 
                     current_date + time '18:00', 
                     interval '10' minute) as gs(ts);

Online example: https://rextester.com/YRNAW81361

Sign up to request clarification or add additional context in comments.

1 Comment

@Zack, yes that's true - but I assumed doing that with timestamps and then discarding the date part of them is even more confusing for someone who has never used generate_series()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.