PySpark-生成日期序列

3

我正在尝试生成日期序列

from pyspark.sql import functions as F

df1 = df.withColumn("start_dt", F.to_date(F.col("start_date"), "yyyy-mm-dd")) \
        .withColumn("end_dt", F.to_date(F.col("end_date"), "yyyy-mm-dd"))

df1.select("start_dt", "end_dt").show()
    
print("type(start_dt)", type("start_dt"))
print("type(end_dt)", type("end_dt"))

df2 = df1.withColumn("lineoffdate", F.expr("""sequence(start_dt,end_dt,1)"""))

以下是输出结果

+---------------+----------+
|   start_date  |  end_date|
+---------------+----------+
|     2020-02-01|2020-03-21|
+---------------+----------+

type(start_dt)  <class 'str'>
type(end_dt)  <class 'str'>

由于数据类型不匹配,无法解析'sequence(start_dt, end_dt, 1)':sequence仅支持整数、时间戳或日期类型;第1行位置0;

即使将开始日期和结束日期转换为日期或时间戳,该列的类型仍为字符串,并在生成日期序列时出现上述错误。


我尝试打印模式 |-- start_dt: date(nullable = true) |-- end_dt: date(nullable = true),但不明白为什么序列不起作用。 - Aruna Jayabalu
1个回答

6

您说得没错,它应该与datetimestamp(日历类型)一起使用,但是您犯的唯一错误是将"step"放在sequence中作为integer,而实际上它应该是日历间隔(例如interval 1 day):

df.withColumn("start_date",F.to_date("start_date")) \
  .withColumn("end_date", F.to_date("end_date")) \
  .withColumn(
    "lineofdate", 
     F.expr("""sequence(start_date,end_date,interval 1 day)""") \
  ) \
  .show()

# output: 
# +----------+----------+--------------------+
# |start_date|  end_date|          lineofdate|
# +----------+----------+--------------------+
# |2020-02-01|2020-03-21|[2020-02-01, 2020...|
# +----------+----------+--------------------+

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接