0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

date_truncの使い方

Last updated at Posted at 2023-04-17

4時間に1度実行するバッチを作成していて、4時間の間に更新されたデータを取得したい。
閾値として、0msecちょうどで更新日時を比較したい時にdate_truncを使用したので、その備忘録。
PostgreSQLで記述。

秒で指定した場合

例1:now()=2023-04-18 00:00:00.000000の場合

date_trunc('second', now() - cast('4 hours' as interval))

結果

2023-04-17 20:00:00.000000

例2:now()=2023-04-18 00:59:59.999999の場合

date_trunc('second', now() - cast('4 hours' as interval))

結果

2023-04-17 20:59:59.000000

分で指定した場合

例1:now()=2023-04-18 00:00:00.000000の場合

date_trunc('minute', now() - cast('4 hours' as interval))

結果

2023-04-17 20:00:00.000000

例2:now()=2023-04-18 00:59:59.999999の場合

date_trunc('minute', now() - cast('4 hours' as interval))

結果

2023-04-17 20:59:00.000000

時間で指定した場合

例1:now()=2023-04-18 00:00:00.000000の場合

date_trunc('hour', now() - cast('4 hours' as interval))

結果

2023-04-17 20:00:00.000000

例2:now()=2023-04-18 00:59:59.999999の場合

date_trunc('hour', now() - cast('4 hours' as interval))

結果

2023-04-17 20:00:00.000000

日付で指定した場合

例1:now()=2023-04-18 00:00:00.000000の場合

date_trunc('day', now() - cast('4 hours' as interval))

結果

2023-04-17 00:00:00.000000

例2:now()=2023-04-18 00:59:59.999999の場合

date_trunc('day', now() - cast('4 hours' as interval))

結果

2023-04-17 00:00:00.000000

日時を指定する場合(余談)

now()ではなくて、指定した日時で比較したい場合
例:2023-04-18 23:00:00.000000を指定して、分以下を切り下げた場合

date_trunc('hour', timestamp '2023-04-18 23:00:00.000000' - interval '4 hours');

結果

2023-04-17 19:00:00.000000

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?