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

PySpark中如何将毫秒级bigInt时间戳转为带毫秒的日期格式?

解决PySpark毫秒级时间戳转带毫秒日期格式的问题

你当前用from_unixtime的方法会丢失毫秒精度,因为这个函数仅处理秒级时间戳,即使传入带小数的秒数,也会自动截断小数部分,导致SSS始终为000。正确的做法是先将毫秒级时间戳转为PySpark的Timestamp类型,再用date_format进行格式化,具体步骤如下:

  1. 导入所需函数
    需要用到to_timestamp(转换为时间戳类型)和date_format(格式化日期):

    from pyspark.sql.functions import to_timestamp, date_format, lit
    
  2. 修改转换代码
    先将bigInt类型的毫秒时间戳除以1000得到带小数的秒数,通过to_timestamp转为支持毫秒精度的Timestamp类型,再用date_format格式化为目标格式:

    Format_Date = "yyyy-MM-dd HH:mm:ss.SSS"
    
    df = df.withColumn("H_evenement", date_format(to_timestamp(df["time"] / lit(1000)), Format_Date))
    
  3. 原理说明

    • to_timestamp可以识别带小数的秒数,将其转换为包含毫秒信息的Timestamp类型;
    • date_format支持对Timestamp类型的列进行毫秒级格式化,SSS占位符会正确提取并显示毫秒部分。

内容的提问来源于stack exchange,提问作者François Cheminade

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 04:37:17