You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 02:45:15