PySpark中将列转为Date类型后如何获取年月?调用strftime报错
PySpark中提取日期的年份和月份解决方案
你遇到的TypeError: 'Column' object is not callable是因为strftime是Python原生datetime对象的方法,而PySpark的Column对象并不支持这个方法。要在PySpark中处理日期格式,需要使用PySpark内置的日期函数,以下是两种可行的实现方式:
方法一:直接使用date_format函数
date_format函数可以将日期列直接格式化为指定的字符串格式,适合快速得到YYYY-MM形式的年月值:
from pyspark.sql.functions import col, date_format df = df.filter(....) .withColumn('Date', col('Time').cast('date')) .withColumn('Month', date_format(col('Date'), "%Y-%m"))
如果不需要单独保留Date列,也可以直接对Time列转换后格式化:
df = df.filter(....) .withColumn('Month', date_format(col('Time').cast('date'), "%Y-%m"))
方法二:分别提取年份和月份再拼接
如果需要单独保留年份、月份列,或者对格式有更灵活的控制,可以用year和month函数提取对应字段,再通过format_string拼接成指定格式:
from pyspark.sql.functions import col, year, month, format_string df = df.filter(....) .withColumn('Date', col('Time').cast('date')) .withColumn('Year', year(col('Date'))) .withColumn('Month_Num', month(col('Date'))) .withColumn('Year-Month', format_string("%04d-%02d", col('Year'), col('Month_Num')))
这里%04d确保年份是4位数字,%02d会将个位数的月份补前导零(比如1月变成01)。
内容的提问来源于stack exchange,提问作者n179911a
相关产品推荐
相关产品推荐

