我有一個需要傳遞給各種函式的日期變數。
例如,如果我將變數中的日期設為 12/09/2021,它應該回傳我 01/01/2021
如何在 PySpark 中獲得一年中的第一天
uj5u.com熱心網友回復:
您可以使用截斷部分日期的trunc 函式。
df = spark.createDataFrame([()], [])
(
df
.withColumn('current_date', f.current_date())
.withColumn("year_start", f.trunc("current_date", "year"))
.show()
)
# Output
------------ ----------
|current_date|year_start|
------------ ----------
| 2022-02-23|2022-01-01|
------------ ----------
uj5u.com熱心網友回復:
x = '12/09/2021'
'01/01/' x[-4:]
output: '01/01/2021'
uj5u.com熱心網友回復:
您可以使用date_trunc和to_date來實作這一點,因為后者回傳 aTimestamp而不是 aDate
資料準備
df = pd.DataFrame({
'Date':['2021-01-23','2002-02-09','2009-09-19'],
})
sparkDF = sql.createDataFrame(df)
sparkDF.show()
----------
| Date|
----------
|2021-01-23|
|2002-02-09|
|2009-09-19|
----------
日期截斷和截止日期
sparkDF = sparkDF.withColumn('first_day_year_dt',F.to_date(F.date_trunc('year',F.col('Date')),'yyyy-MM-dd'))\
.withColumn('first_day_year_timestamp',F.date_trunc('year',F.col('Date')))
sparkDF.show()
---------- ----------------- ------------------------
| Date|first_day_year_dt|first_day_year_timestamp|
---------- ----------------- ------------------------
|2021-01-23| 2021-01-01| 2021-01-01 00:00:00|
|2002-02-09| 2002-01-01| 2002-01-01 00:00:00|
|2009-09-19| 2009-01-01| 2009-01-01 00:00:00|
---------- ----------------- ------------------------
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/432269.html
下一篇:所有月份結束,直到結束日期
