달나라 노트

Presto : date_trunc (지정한 날짜 단위 기준으로 날짜 자르기) 본문

SQL/Presto

Presto : date_trunc (지정한 날짜 단위 기준으로 날짜 자르기)

CosmosProject 2025. 10. 18. 12:19
728x90
반응형

 

 

 

 

Syntax

date_trunc('datepart', date/timestamp)

date_trunc 함수는 위처럼 사용할 수 있습니다.

주어진 date를 명시한 datepart까지만 남기고 그 이하는 모두 자른 후(모두 가장 작은 값으로 만든 후) timestamp를 반환합니다.

 

 

 

 

select  current_timestamp as current_dttm  --> 2025-09-18 03:23:12.907
        , date_trunc('year', current_timestamp) as trunc_year  --> 2025-01-01 00:00:00.000
        , date_trunc('quarter', current_timestamp) as trunc_quarter  --> 2025-07-01 00:00:00.000
        , date_trunc('month', current_timestamp) as trunc_month  --> 2025-09-01 00:00:00.000
        , date_trunc('week', current_timestamp) as trunc_week  --> 2025-09-15 00:00:00.000
        , date_trunc('day', current_timestamp) as trunc_day  --> 2025-09-18 00:00:00.000
;

위 예시를 봅시다.

주어진 시점은 2025-09-18 03:23:12.907입니다.

 

 

- date_trunc('year', current_timestamp)

date_trunc에 year를 전달하면 주어진 날짜의 년도인 2025년의 시작점을 return해줍니다.

그래서 2025-01-01 00:00:00.000 이라는 결과가 나왔습니다.

 

- date_trunc('quarter', current_timestamp)

date_trunc에 quarter를 전달하면 주어진 날짜의 분기인 3분기(9월 18일은 3분기죠)의 시작점을 return해줍니다.

그래서 2025-07-01 00:00:00.000 이라는 결과가 나왔습니다. (3분기의 시작은 7월 1일입니다.)

 

- date_trunc('month', current_timestamp)

date_trunc에 month를 전달하면 주어진 날짜의 월인 9월의 시작점을 return해줍니다.

그래서 2025-09-01 00:00:00.000 이라는 결과가 나왔습니다.

 

- date_trunc('week', current_timestamp)

date_trunc에 week를 전달하면 주어진 날짜가 속한 주차의 시작점을 return해줍니다.

2025년 9월 18일은 목요일이며 한 주의 시작은 월요일로 간주됩니다.

그래서 2025-09-15 00:00:00.000 이라는 결과가 나왔습니다. (2025년 9월 15일은 월요일입니다.)

 

- date_trunc('day', current_timestamp)

date_trunc에 day를 전달하면 주어진 날짜가 속한 일자의 시작점을 return해줍니다.

그래서 2025-09-18 00:00:00.000 이라는 결과가 나왔습니다.

 

 

 

 

select  current_timestamp as current_dttm  --> 2025-09-18 03:23:12.907
        , date_trunc('hour', current_timestamp) as trunc_hour  --> 2025-09-18 03:00:00.000
        , date_trunc('minute', current_timestamp) as trunc_minute  --> 2025-09-18 03:23:00.000
        , date_trunc('second', current_timestamp) as trunc_second  --> 2025-09-18 03:23:12.000
;

 

date_trunc는 날짜가 아닌 시간에도 사용할 수 있습니다.

위처럼 hour, minute, second를 전달하면 각각 시간, 분, 초를 기준으로 각각의 시작점으로 잘린 값들이 return된 것을 볼 수 있습니다.

 

 

 

 

FYI

https://prestodb.io/docs/current/functions/datetime.html#dow-x-bigint

 

Date and Time Functions and Operators - Presto 0.295 Documentation

Date and Time Functions and Operators Date and Time Operators Operator Example Result + date '2012-08-08' + interval '2' day 2012-08-10 + time '01:00' + interval '3' hour 04:00:00.000 + timestamp '2012-08-08 01:00' + interval '29' hour 2012-08-09 06:00:00.

prestodb.io

 

 

 

728x90
반응형
Comments