PostgreSQL Get a random datetime/timestamp between two datetime/timestamp

后端 未结 3 1699
暗喜
暗喜 2020-12-29 02:12

The title is pretty much explicit, my question is if i get two dates with hour:

  • 01-10-2014 10:00:00
  • 01-20-2014 20:00:00

Is it possible

3条回答
  •  余生分开走
    2020-12-29 02:53

    You could build the timestamp from a random integer (unix stamp), e.g.:

    select timestamp 'epoch' + (
              extract('epoch' from timestamp '2014-10-01 10:00:00')
            + random() * (
                         extract('epoch' from timestamp '2014-20-01 20:00:00')
                       - extract('epoch' from timestamp '2014-10-01 10:00:00')
           )) * interval '1 second'
    

    Wrap it in an SQL function if you use it often, as it's not very readable even after attempting to format it somewhat.

    Another way to do it would be to use generate_series() from the start date to the end date, ordered by random(), but that would make things very slow with larger date intervals so you'll be better off with the above approach.

提交回复
热议问题