我有一个日期变量,需要传递给各种函数。
例如,如果变量中的日期为12/09/2021,则应返回01/01/2021
我在PySpark怎么过一年的第一天?
发布于 2022-02-23 12:40:18
您可以使用截断日期部分的中继函数。
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|
+------------+----------+发布于 2022-02-23 12:41:19
x = '12/09/2021'
'01/01/' + x[-4:]output: '01/01/2021'发布于 2022-02-23 12:43:36
您可以使用警棍使用日期实现这一点,因为后者返回的是Timestamp而不是Date。
数据准备
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|
+----------+日期: Trunc &至今
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://stackoverflow.com/questions/71236904
复制相似问题