简体   繁体   中英

How to create new string column extracting integers from a timestamp in Spark?

I have a spark dataframe with a timestamp column, I want a new column which has strings in the format "YYYYMM".

I tried with:

df.withColumn('year_month',year(col("timestamp")).cast("string")+month(col("timestamp")).cast("string"))

But if my timestamp is 2016-10-12, it returns as 2020 as YYYYMM.

You can use date_format :

from pyspark.sql.functions import date_format
df.withColumn('year_month', date_format('timestamp', 'yyyyMM'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM