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

如何将PySpark Row中的datetime.date转换为yyyy-mm-dd字符串格式

解决方案:将PySpark Row中的datetime.date转为yyyy-mm-dd字符串列表

方法一:在SQL查询阶段直接格式化(推荐)

利用Spark SQL的date_format函数,在查询时就把日期转成目标格式的字符串,避免后续在Driver端处理大量数据,效率更高。

query = "select date_format(device_date, 'yyyy-MM-dd') as device_date from device where device is not null"
res = spark.sql(query).collect()

if len(res) != 0:
    # 提取Row中的字符串值生成列表
    return [row.device_date for row in res[:20]]

方法二:在Python端处理已收集的Row列表

如果已经完成数据收集,可通过datetime.date对象的strftime方法逐个转换格式:

query = "select device_date from device where device is not null"
res = spark.sql(query).collect()

if len(res) != 0:
    # 将每个date对象转为指定格式的字符串
    return [row.device_date.strftime('%Y-%m-%d') for row in res[:20]]

注意事项

  • strftime参数里的%Y代表4位年份,%m代表两位月份,%d代表两位日期,必须严格区分大小写,比如小写%y是两位年份,不要混淆。
  • 优先选择方法一,尤其是数据量较大时,分布式处理的性能远优于Driver端单节点处理。

内容的提问来源于stack exchange,提问作者vvazza

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 13:55:18