hive 中的 date_trunc 工作不正确

问题描述 投票:0回答:3

我正在运行以下查询:

select a.event_date,
    date_format(date_trunc('month', a.event_date), '%m/%d/%Y') as date
from monthly_test_table a
order by 1;

输出:

 2017-09-15 | 09/01/2017
 2017-10-01 | 09/30/2017
 2017-11-01 | 11/01/2017

谁能告诉我为什么日期“2017-10-01”在使用 date_trunc 后显示的日期为“09/30/2017”。

提前致谢...!

hive presto
3个回答
0
投票

您正在反向格式化,所以它是不正确的。 使用以下代码

select a.event_date,
    date_format(date_trunc('month', a.event_date), '%Y/%m/%d') as date
from monthly_test_table a
order by 1;

0
投票

您可以使用

date_add
和逻辑减去 1 天(您的日期)来复制
trunc

例如:

2017-10-01 - day('2017-10-01') is 1 and you add 1-1=0 days 
2017-08-30 - day('2017-08-30') is 30 and you add 1-30=-29 days 

我最近遇到了同样的问题,并诉诸使用这种逻辑。

date_add(from_unixtime(unix_timestamp(event_date,'yyyy-MM-dd'),'yyyy-MM-dd'),
         1-day(from_unixtime(unix_timestamp(event_date,'yyyy-MM-dd'),'yyyy-MM-dd'))
        )

PS:据我所知,

date_trunc
中没有
Hive documentation
功能。


0
投票

根据下面的源代码:

UTC_CHRONOLOGY
时间被翻译为w.r.t。 locale,也在
Description
中提到会话时区将是精度,另请参阅下面的URL。

@Description("truncate to the specified precision in the session timezone")
@ScalarFunction("date_trunc")
@LiteralParameters("x")
@SqlType(StandardTypes.DATE)
public static long truncateDate(ConnectorSession session, @SqlType("varchar(x)") Slice unit, @SqlType(StandardTypes.DATE) long date)
{
    long millis = getDateField(UTC_CHRONOLOGY, unit).roundFloor(DAYS.toMillis(date));
    return MILLISECONDS.toDays(millis);
}

参见https://prestodb.io/docs/current/release/release-0.66.html:::

时区:
此版本完全支持时区规则,这是正确执行日期/时间计算所必需的。通常,会话时区用于时间计算。这是提交查询的客户端计算机的时区(如果有)。否则,它是运行 Presto 协调器的服务器的时区。

使用夏令时后的时区进行操作的查询可以 产生意想不到的结果。 例如,如果我们运行以下查询 添加 24 小时使用美国/洛杉矶时区:

SELECT date_add('小时', 24, TIMESTAMP '2014-03-08 09:00:00');

输出:2014-03-09 10:00:00.000

© www.soinside.com 2019 - 2024. All rights reserved.