【问题标题】:How can I print milliseconds in Hive without ignoring zeros如何在 Hive 中打印毫秒而不忽略零
【发布时间】:2023-04-04 21:50:01
【问题描述】:

我正在尝试打印 'YYYY-MM-d HH:mm:ss.S',它最后精确到 3 毫秒。

这是我通常得到的。

hive> select current_timestamp();
OK
2020-09-22 12:00:26.658

但在极端情况下我也会得到

hive> select current_timestamp();
OK
2020-09-22 12:00:25.5
Time taken: 0.065 seconds, Fetched: 1 row(s)

hive> select cast(current_timestamp() as timestamp);
OK
2020-09-22 12:00:00.09
Time taken: 0.084 seconds, Fetched: 1 row(s)

hive> select current_timestamp() as string;
OK
2020-09-22 11:07:12.27
Time taken: 0.076 seconds, Fetched: 1 row(s)

我期待的是不要忽略末尾的 0,例如:

hive> select current_timestamp();
OK
2020-09-22 12:00:25.500
Time taken: 0.065 seconds, Fetched: 1 row(s)

hive> select cast(current_timestamp() as timestamp);
OK
2020-09-22 12:00:00.090
Time taken: 0.084 seconds, Fetched: 1 row(s)

hive> select current_timestamp();
OK
2020-09-22 11:07:12.270
Time taken: 0.076 seconds, Fetched: 1 row(s)

我尝试了什么:

hive> select from_unixtime(unix_timestamp(),'yyyy-MM-dd HH:MM:ss.S');
unix_timestamp(void) is deprecated. Use current_timestamp instead.
OK
2020-09-22 11:09:30.0
Time taken: 0.064 seconds, Fetched: 1 row(s)

我还尝试将 current_timestamp() 转换为字符串,这样它就不会忽略 0,但这也不起作用

【问题讨论】:

    标签: sql string datetime hive hiveql


    【解决方案1】:

    试试rpad(string str, int len, string pad)

    Doc:

    返回 str,用 pad 向右填充到 len 的长度。如果 str 比 len 长,则返回值缩短为 len 个字符。如果填充字符串为空,则返回值为 null。

    【讨论】:

      【解决方案2】:

      如果你使用date_format(),它会起作用吗?

      select date_format(current_timestamp, 'yyyy-MM-dd HH:mm:ss.SSS')
      

      【讨论】:

      • 是的,我刚试过,说 to_char 是无效函数。
      • @settle:我的错,我对另一个 Apache 产品感到困惑。 date_format() 应该这样做(使用相同的格式说明符)。查看我的编辑。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-16
      • 1970-01-01
      • 1970-01-01
      • 2020-10-13
      • 2020-12-28
      相关资源
      最近更新 更多