PySpark转换epoch时间戳为日期时输出错误结果问题求解
问题原因
你使用的event_time字段是毫秒级的Unix时间戳,但Spark SQL的from_unixtime函数默认接收的是秒级的Unix时间戳,直接传入毫秒值会导致时间计算偏移,才会出现5万多年的错误结果。
正确转换方法
方法1:将毫秒级时间戳除以1000转为秒级再处理
直接对event_time做除法取秒级值后传入from_unixtime即可:
parsed_df.withColumn( "event_date", from_unixtime(col('event_time').cast('long') / 1000).alias("event_date") ).select("event_time", "event_date").limit(10).show()
方法2:使用to_timestamp函数直接指定时间单位
Spark 2.2+版本支持to_timestamp函数直接指定时间戳的单位,写法更直观:
from pyspark.sql.functions import to_timestamp parsed_df.withColumn( "event_date", to_timestamp(col('event_time').cast('long'), unit='ms').alias("event_date") ).select("event_time", "event_date").limit(10).show()
如果后续只需要日期不需要时分秒,可以在上面的基础上调用to_date函数:
# 基于方法2的示例,只保留日期 from pyspark.sql.functions import to_date, to_timestamp parsed_df.withColumn( "event_date", to_date(to_timestamp(col('event_time').cast('long'), unit='ms')).alias("event_date") ).select("event_time", "event_date").limit(10).show()
内容的提问来源于stack exchange,提问作者Gaurang Shah
相关产品推荐
相关产品推荐

