我正在尝试生成一个日期序列
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;
即使在将开始日期和结束日期转换为日期或时间戳后,我仍然看到列的类型仍然是 str 并且在生成日期序列时出现上述错误。
最佳答案
你说它应该与 date
或 timestamp
(日历类型)一起使用是正确的,但是,你犯的唯一错误是你把
为 sequence
中的“step”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...|
# +----------+----------+--------------------+
关于date - pyspark-生成日期序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60725411/