在 PySpark 中读取包含时间戳的 CSV 文件可以通过以下步骤实现:
CSV(Comma-Separated Values)文件是一种常见的数据存储格式,每行代表一条记录,字段之间用逗号分隔。时间戳通常表示为自 1970 年 1 月 1 日以来的秒数或毫秒数。
假设 CSV 文件 data.csv
包含以下内容:
id,timestamp,value
1,1633024800000,100
2,1633028400000,200
3,1633032000000,300
以下是读取 CSV 文件并处理时间戳的示例代码:
from pyspark.sql import SparkSession
from pyspark.sql.functions import from_unixtime, col
# 创建 SparkSession
spark = SparkSession.builder \
.appName("Read Timestamp CSV") \
.getOrCreate()
# 读取 CSV 文件
df = spark.read.csv("data.csv", header=True, inferSchema=True)
# 将时间戳列转换为日期时间格式
df = df.withColumn("timestamp", from_unixtime(col("timestamp") / 1000).cast("timestamp"))
# 显示结果
df.show()
SparkSession
连接到 Spark 集群。spark.read.csv
方法读取 CSV 文件,并设置 header=True
和 inferSchema=True
以自动推断列名和数据类型。from_unixtime
函数将 Unix 时间戳转换为日期时间格式,并将其转换为 timestamp
类型。df.show()
方法显示处理后的数据。通过以上步骤,你可以成功读取包含时间戳的 CSV 文件,并将其转换为可处理的日期时间格式。
领取专属 10元无门槛券
手把手带您无忧上云