PySpark SQL 函數的date_format(~) 方法將日期、時間戳或字符串轉換為指定格式的日期字符串。
參數
1.date | Column 或 string
日期列 - 可以是日期、時間戳或字符串類型。
2. format | string
生成的日期字符串的格式。
返回值
日期字符串的 Column 對象。
例子
格式化 PySpark DataFrame 中的日期字符串
考慮以下帶有一些日期字符串的 PySpark DataFrame:
df = spark.createDataFrame([["Alex", "1995-12-16"], ["Bob", "1998-05-06"]], ["name", "birthday"])
df.show()
+----+----------+
|name|  birthday|
+----+----------+
|Alex|1995-12-16|
| Bob|1998-05-06|
+----+----------+要轉換列 birthday 中的日期字符串:
from pyspark.sql import functions as F
df.select(F.date_format("birthday", "dd/MM/yyyy").alias("birthday_new")).show()
+------------+
|birthday_new|
+------------+
|  16/12/1995|
|  06/05/1998|
+------------+這裏,:
- 
"dd/MM/yyyy"表示以日、月、年開頭的日期字符串。
- 
alias(~)用於為date_format(~)返回的Column對象命名。
格式化 PySpark DataFrame 中的日期時間值
考慮以下帶有一些日期時間值的 PySpark DataFrame:
import datetime
df = spark.createDataFrame([["Alex", datetime.date(1995,12,16)], ["Bob", datetime.date(1995,5,9)]], ["name", "birthday"])
df.show()
+----+----------+
|name|  birthday|
+----+----------+
|Alex|1995-12-16|
| Bob|1995-05-09|
+----+----------+要轉換列 birthday 中的日期時間值:
df.select(F.date_format("birthday", "dd-MM-yyyy").alias("birthday_new")).show()
+------------+
|birthday_new|
+------------+
|  16-12-1995|
|  06-05-1998|
+------------+在這裏,我們使用日期格式 "dd-MM-yyyy" ,這意味著先是日,然後是月,然後是年。我們還將列名 "birthday_new" 分配給 date_format() 返回的 Column 。
相關用法
- Python PySpark SQL Functions date_add方法用法及代碼示例
- 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_format method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
