Apache spark pyspark将数据帧列从时间戳转换为字符串;YYYY-MM-DD“;格式

Apache spark pyspark将数据帧列从时间戳转换为字符串;YYYY-MM-DD“;格式,apache-spark,pyspark,Apache Spark,Pyspark,在pyspark中,是否有方法将时间戳数据类型的数据帧列转换为格式为“YYYY-MM-DD”的字符串?您可以使用以下函数 from pyspark.sql.functions import date_format df.withColumn("DateOnly", date_format('DateTime', "yyyy-MM-dd")).show() from pyspark.sql.functions import date_format df.withColumn("dateCo

在pyspark中,是否有方法将时间戳数据类型的数据帧列转换为格式为“YYYY-MM-DD”的字符串?

您可以使用以下函数

from pyspark.sql.functions  import date_format

df.withColumn("DateOnly", date_format('DateTime', "yyyy-MM-dd")).show()
from pyspark.sql.functions import date_format

df.withColumn("dateColumn",  date_format(col("vacationdate"), "yyyy-MM-dd"))

希望这有帮助

如果您有一列带有
schema
as

root
 |-- date: timestamp (nullable = true)
然后,您可以使用
from_unixtime
函数在使用
unix_timestamp
函数将时间戳转换为bigInt后,将时间戳转换为字符串

from pyspark.sql import functions as f
df.withColumn("date", f.from_unixtime(f.unix_timestamp(df.date), "yyyy-MM-dd"))
你应该有

root
 |-- date: string (nullable = true)

请在代码中添加一些解释。你好,Ramesh,通常时间戳的格式为2012-01-01 00:00:00。我们能否将其格式化为2012年1月,同时将其模式保持为date:timestamp?如果我们使用date_format(),我们会得到一个字符串。我们应该使用哪个函数将时间戳格式化为我们想要的格式,同时仍将其保留为时间戳,而不是无意中将其转换为date:string?延迟到第三方,但您可以使用下面的代码将任何字符串转换为时间戳
#udf将数据类型更改为timestamp change_to_timestamp_fmt=udf(lambda x:datetime.strtime(x,'%d-%b-%Y%H:%M:%S'),TimestampType())
@anidev711 pyspark中的udf通常比本机spark(scala/java)函数慢10到10000倍,原因显而易见。仅供参考,您可以根据需要调整日期格式。我只需要月份和年份,
yyyy-MM
。看起来还可以