Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Postgres generate series with exactly 100 steps

Lets say we have the dates

'2017-01-01'
and
'2017-01-15'

and I would like to get a series of exactly N timestamps in between these dates, in this case 7 dates:

SELECT * FROM 
    generate_series_n(
        '2017-01-01'::timestamp,
        '2017-01-04'::timestamp,
        7
    )

Which I would like to return something like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

2017-01-01-00:00:00
2017-01-01-12:00:00
2017-01-02-00:00:00
2017-01-02-12:00:00
2017-01-03-00:00:00
2017-01-03-12:00:00
2017-01-04-00:00:00

How can I do this in postgres?

>Solution :

You can divide the difference between the end and the start value by the number of values you want:

SELECT * 
FROM generate_series('2017-01-01'::timestamp, 
                     '2017-01-04'::timestamp, 
                     ('2017-01-04'::timestamp - '2017-01-01'::timestamp) / 7)

This could be wrapped into a function if you want to avoid repeating the start and end value.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading