Python Pyspark:如何在读取csv文件时将unix时间戳转换为日期
我有一个.csv,如下所示Python Pyspark:如何在读取csv文件时将unix时间戳转换为日期,python,apache-spark,pyspark,Python,Apache Spark,Pyspark,我有一个.csv,如下所示 Timestamp, Name, Value 1577862435, BatteryA, 0.25 1577915618, BatteryB, 0.50 1577839734, BatteryC, 0.34 我定义了一个模式 schema = StructType([ StructField("timestamp", IntegerType(), True), StructField("Name", StringType(),
Timestamp, Name, Value
1577862435, BatteryA, 0.25
1577915618, BatteryB, 0.50
1577839734, BatteryC, 0.34
我定义了一个模式
schema = StructType([
StructField("timestamp", IntegerType(), True),
StructField("Name", StringType(), True),
StructField("Value", FloatType(), True)])
df = spark.read.format('csv').option("delimiter", "\t").schema(schema).load("myFile.csv")
在我读取Unix时间戳时,如何以日期的形式直接读取它?您可以使用时间戳类型:
更新
所以很明显,您不能直接将历元时间戳读取为时间戳类型,它必须在这之前转换为
我建议你:
schema = StructType([
StructField("timestamp", LongType(), True),
StructField("Name", StringType(), True),
StructField("Value", FloatType(), True)])
df = spark.read.format('csv').option("delimiter", "\t").schema(schema).load("myFile.csv")
df = df.withColumn("timestamp", df["timestamp"].cast(TimestampType()))
你是对的。我刚才自己测试过。看看我的最新答案我得到了这个错误名称错误:名称'res'没有定义对不起,这是一个复制过去的错误。看上面现在我得到了名称错误:名称“withColumn”没有定义让我们来看看。
schema = StructType([
StructField("timestamp", LongType(), True),
StructField("Name", StringType(), True),
StructField("Value", FloatType(), True)])
df = spark.read.format('csv').option("delimiter", "\t").schema(schema).load("myFile.csv")
df = df.withColumn("timestamp", df["timestamp"].cast(TimestampType()))