Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 to pick a random datetime between these two datetime ?

I tried with the random() function but i don't really get how to use it with datetime

Thanks

Matthiew

like image 203
Matthiew Avatar asked Apr 09 '14 13:04

Matthiew


People also ask

How do I get random date in PostgreSQL?

In Postgresql, we can generate random dates between two dates with help of two functions random( ) and now( ). random( ) : It is the random function that returns a value between 0 (inclusive) and 1 (exclusive), so value >= 0 and value < 1.

How do I calculate days between two dates in PostgreSQL?

In PostgreSQL, if you subtract one datetime value (TIMESTAMP, DATE or TIME data type) from another, you will get an INTERVAL value in the form ”ddd days hh:mi:ss”. So you can use DATE_PART function to extact the number of days, but it returns the number of full days between the dates.

Is there datediff in PostgreSQL?

PostgreSQL provides a datediff function to users. The datediff means we can return the difference between two dates based on their specified interval. The datediff function plays an important role in the database management system because datediff functions as a calendar and it is very helpful to users.

How do I create an interval in PostgreSQL?

In PostgreSQL, the make_interval() function creates an interval from years, months, weeks, days, hours, minutes and seconds fields. You provide the years, months, weeks, days, hours, minutes and/or seconds fields, and it will return an interval in the interval data type.


1 Answers

You can do almost everything with the date/time operators:

select timestamp '2014-01-10 20:00:00' +        random() * (timestamp '2014-01-20 20:00:00' -                    timestamp '2014-01-10 10:00:00') 
like image 101
pozs Avatar answered Oct 11 '22 23:10

pozs