[英]How to create a composite datetime with fixed date + random time interval in Postgresql
I'm new to Postgresql, and I'm looking for a way to return a composite datetime, built with a fixed date, and a random time, defined as an interval.我是 Postgresql 的新手,我正在寻找一种返回复合日期时间的方法,该日期时间由固定日期和随机时间(定义为间隔)构建。
An example:一个例子:
2020-12-02 10:00:00
2020-12-02 10:10:20
2020-12-02 08:25:23
2020-12-02 09:12:11
As you can see the date is fixed, and time remains between 08:00:00 and 10:30:00.如您所见,日期是固定的,时间保持在 08:00:00 到 10:30:00 之间。
Do you know how to replicate this behaviour using a Postgresql query?您知道如何使用 Postgresql 查询来复制此行为吗?
As a total newbie of Postgresql (but with some experience in general SQL), and reading some posts here, I've found an easy way to get it done:作为 Postgresql 的总新手(但有一些一般 SQL 的经验),并在这里阅读一些帖子,我找到了一个简单的方法来完成它:
SELECT
CURRENT_DATE + time '08:00:00' +
(random() * interval '3 hours')::time
AS date_wrandom_t
FROM generate_series(1, 50)
generate_series
its here only to demonstrate some results, you can omit it and get a single result. generate_series
在这里只是为了展示一些结果,你可以省略它并得到一个结果。
What it does:它能做什么:
SELECT (random() * interval '3 hours')::time
)SELECT (random() * interval '3 hours')::time
测试) Maybe it's not the best solution, but I like it as it's based on a simple syntax, easy to remember.也许这不是最好的解决方案,但我喜欢它,因为它基于简单的语法,易于记忆。
I wish to find some time to study this DBMS, it seems really powerful.我想找点时间研究一下这个DBMS,它看起来真的很强大。
Any addition/suggestion is welcome!欢迎任何补充/建议!
I would suggest:我会建议:
select '2020-12-02 08:00:00'::timestamp + random() * interval '2 hour 30 minute'
Or, for the current date, you could express this as:或者,对于当前日期,您可以将其表示为:
select current_date + interval '08:00:00' + random() * interval '02:30'
Note that these illustrate two different ways of expressing an interval with 2 hours and 30 minutes (and not even giving interval '150 minute'
as an example).请注意,这些说明了用 2 小时和 30 分钟表示间隔的两种不同方式(甚至没有给出
interval '150 minute'
作为示例)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.