简体   繁体   中英

Getting random time interval in postgreSQL

I need random interval time between 0 and (10 days and 5 hours).

My code:

select random() * (interval '10 days 5 hours')
from generate_series(1, 50)

It works like should, except a few strange results, like:

0 years 0 mons 7 days 26 hours 10 mins 1.353353 secs

The problem is 26 hours, it shouldn't be more than 23. And I never get 10 days, what I'd like to.

Intervals in Postgres are quite flexible, so hour values of greater than 23 do not necessarily roll over to days. Use jusify_interval() to return them to the normal "days" and "hours"."

So:

select justify_interval(random() * interval '10 day 5 hour')
from generate_series(1, 200)
order by 1 desc;

will return values with appropriate values for days, hours, minutes, and seconds.

Now, why aren't you getting intervals with more than 10 days? This is simple randomness. If you increase the number of rows to 200 (as above), you'll see them (in all likelihood). If you run the code multiple times, sometimes you'll see none in that range; sometimes you'll see two.

Why? You are asking how often you get a value of 240+ in a range of 245. Those top 5 hours account for 0.02% of the range (about 1/50). In other words a sample of 50 is not big enough -- any given sample of 50 random values is likely to be missing 1 or more 5 hour ranges.

Plus, without justify_interval() , you are likely to miss those anyway because they may show up as 9 days with an hours component larger than 23.

Try this:

select justify_hours(random() * (interval '245 hours'))
FROM generate_series(1, 50)

See Postgres Documentation for an explanation of the justify_* functions.

One option would be to use an interval of one hour, and then multiply by the random number between 0 and 1 coming from the series:

select random() * 245 * interval '1 hour'
from generate_series(1, 50);

I can see that the other answers suggest using justify_interval . If you just want a series of intervals between 0 and 245 hours (245 hours corresponding to 10 days and 5 hours), then my answer should suffice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM