You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spark SQL中date_format输出时间戳含多余毫秒的问题求助

Spark date_format输出多余毫秒的解决办法

问题原因

你用date_format指定格式后仍出现毫秒,本质是因为Spark的CURRENT_TIMESTAMP是带毫秒的Timestamp类型,若后续操作中结果被隐式转回Timestamp类型,Spark会自动补全三位毫秒(即使原格式没指定)。之前用unix_timestamp的方法无效,也是因为from_unixtime生成的字符串被隐式转成了Timestamp。

有效解决方案

  • 强制转为字符串类型:确保最终输出是字符串而非Timestamp,彻底避免毫秒补全:

    // Scala API
    date_format(CURRENT_TIMESTAMP, "yyyy-MM-dd HH:mm:ss").cast(StringType)
    
    -- SQL 语法
    CAST(date_format(CURRENT_TIMESTAMP, 'yyyy-MM-dd HH:mm:ss') AS STRING)
    
  • 先截断到秒再格式化:从根源上移除毫秒部分后再格式化,无需担心类型转换问题:

    // Scala API
    date_format(date_trunc("second", CURRENT_TIMESTAMP), "yyyy-MM-dd HH:mm:ss")
    
    -- SQL 语法
    date_format(date_trunc('second', CURRENT_TIMESTAMP), 'yyyy-MM-dd HH:mm:ss')
    

内容的提问来源于stack exchange,提问作者John Constantine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 10:04:55