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

使用pandas时如何将Timestamp的timeUnit从微秒改为毫秒?

解决Spark Schema中Timestamp时间单位为微秒转毫秒的问题

针对你的需求,这里提供几种实用方案:

方案1:调整Pandas时间序列精度后转Spark DataFrame

Pandas默认生成的datetime64是纳秒精度,转Spark时会被映射为微秒级Timestamp。可以先把时间序列的精度降到毫秒:

# 按原格式解析时间
timestamps = pd.to_datetime(table[0], format='%m/%d/%Y %H:%M:%S %p')
# 将时间精度转换为毫秒级
timestamps = timestamps.astype('datetime64[ms]')
# 转换为Spark DataFrame
spark_df = spark.createDataFrame(pd.DataFrame({'timeWithOffset': timestamps}))

此时Spark Schema里的timeWithOffset字段时间单位会自动变为毫秒。

方案2:创建Spark DataFrame时显式指定精度Schema

Spark 3.0及以上版本支持指定Timestamp的精度,直接在Schema里定义毫秒精度即可:

from pyspark.sql.types import StructType, StructField, TimestampType

# 解析时间
timestamps = pd.to_datetime(table[0], format='%m/%d/%Y %H:%M:%S %p')
df = pd.DataFrame({'timeWithOffset': timestamps})

# 定义带毫秒精度的Schema(3代表10^-3秒,即毫秒)
schema = StructType([
    StructField("timeWithOffset", TimestampType(3), nullable=True)
])

# 按指定Schema生成Spark DataFrame
spark_df = spark.createDataFrame(df, schema=schema)

方案3:通过整数时间戳转换实现

先把Pandas时间转为毫秒级整数时间戳,再在Spark中转为指定精度的Timestamp:

# 解析时间并转为毫秒级整数时间戳
timestamps = pd.to_datetime(table[0], format='%m/%d/%Y %H:%M:%S %p').astype('int64') // 10**6
df = pd.DataFrame({'timeWithOffset': timestamps})

# 定义毫秒精度的Schema
schema = StructType([
    StructField("timeWithOffset", TimestampType(3), nullable=True)
])

# 创建Spark DataFrame
spark_df = spark.createDataFrame(df, schema=schema)

内容的提问来源于stack exchange,提问作者Nithya Narva

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 14:06:25