PySpark 的 date_add(-) 方法將指定的天數添加到日期列。
參數
1.start |
開始日期列。
2. days | int
要添加的天數。
返回值
pyspark.sql.column.Column 對象。
例子
基本用法
考慮以下 DataFrame :
df = spark.createDataFrame([["2023-04-20"], ["2023-04-22"]], ["my_date"])
df.show()
+----------+
|   my_date|
+----------+
|2023-04-20|
|2023-04-22|
+----------+要在我們的專欄中添加 5 天:
from pyspark.sql import functions as F
df.select(F.date_add("my_date", 5)).show()
+--------------------+
|date_add(my_date, 5)|
+--------------------+
|          2023-04-25|
|          2023-04-27|
+--------------------+將一列天數添加到一列日期中
不幸的是,date_add(-) 方法僅接受第二個參數的常量。要將一列天添加到一列日期中,我們必須采取另一種方法。
為了進行演示,請考慮以下PySpark DataFrame:
df = spark.createDataFrame([["2023-04-20", 3], ["2023-04-22", 5]], ["my_date", "my_days"])
df.show()
+----------+-------+
|   my_date|my_days|
+----------+-------+
|2023-04-20|      3|
|2023-04-22|      5|
+----------+-------+要將 my_days 添加到 my_date ,請在  F.expr()  方法中提供以下 SQL 方法,如下所示:
# Cast to INT first - by default, intgers have type BIGINT (F.expr(-) with raise an error)
df = df.withColumn("my_days", df["my_days"].cast("int"))
df_new = df_new.withColumn("new_date", F.expr("date_add(my_date, my_days)"))
df_new.show()
+----------+-------+----------+
|   my_date|my_days|  new_date|
+----------+-------+----------+
|2023-04-20|      3|2023-04-23|
|2023-04-22|      5|2023-04-27|
+----------+-------+----------+所得列的數據類型如下:
df_new.printSchema()
root
 |-- my_date: string (nullable = true)
 |-- days: integer (nullable = true)
 |-- new_date: date (nullable = true)請注意,盡管 my_date 的類型為 string ,但生成的 new_date 的類型為 date 。
相關用法
- Python PySpark SQL Functions date_format方法用法及代碼示例
- Python PySpark SQL Functions dayofmonth方法用法及代碼示例
- Python PySpark SQL Functions dayofweek方法用法及代碼示例
- Python PySpark SQL Functions dayofyear方法用法及代碼示例
- Python PySpark SQL Functions split方法用法及代碼示例
- Python PySpark SQL Functions repeat方法用法及代碼示例
- Python PySpark SQL Functions explode方法用法及代碼示例
- Python PySpark SQL Functions concat方法用法及代碼示例
- Python PySpark SQL Functions instr方法用法及代碼示例
- Python PySpark SQL Functions count_distinct方法用法及代碼示例
- Python PySpark SQL Functions array方法用法及代碼示例
- Python PySpark SQL Functions concat_ws方法用法及代碼示例
- Python PySpark SQL Functions col方法用法及代碼示例
- Python PySpark SQL Functions translate方法用法及代碼示例
- Python PySpark SQL Functions expr方法用法及代碼示例
- Python PySpark SQL Functions regexp_extract方法用法及代碼示例
- Python PySpark SQL Functions regexp_replace方法用法及代碼示例
- Python PySpark SQL Functions round方法用法及代碼示例
- Python PySpark SQL Functions countDistinct方法用法及代碼示例
- Python PySpark SQL Functions collect_list方法用法及代碼示例
- Python PySpark SQL Functions lit方法用法及代碼示例
- Python PySpark SQL Functions upper方法用法及代碼示例
- Python PySpark SQL Functions length方法用法及代碼示例
- Python PySpark SQL Functions trim方法用法及代碼示例
- Python PySpark SQL Functions month方法用法及代碼示例
注:本文由純淨天空篩選整理自Isshin Inada大神的英文原創作品 PySpark SQL Functions | date_add method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
