我有一個如下所示的資料集:
--- ----------
|id |t_date |
--- ----------
|1 |1635234395|
|1 |1635233361|
--- ----------
其中t_date包含epoch今天日期的秒數。現在,我想將其轉換為時間戳。我嘗試了下面的代碼,但它給出了錯誤的輸出:

我提到了以下兩個鏈接,但沒有運氣:
- 如何使用 Java 將 Apache spark DataFrame 中的 unix epoch 列轉換為 Date?
- 使用 udf 在 PySpark 資料框中將紀元轉換為日期時間
uj5u.com熱心網友回復:
您不必將其除以1000,您可以輕松使用from_unixtime
資料準備
input_str = """
1,1635234395,
1,1635233361
""".split(",")
input_values = list(map(lambda x: x.strip() if x.strip() != 'null' else None, input_str))
cols = list(map(lambda x: x.strip() if x.strip() != 'null' else None, "id,t_date".split(',')))
n = len(input_values)
n_col = 2
input_list = [tuple(input_values[i:i n_col]) for i in range(0,n,n_col)]
input_list
sparkDF = sql.createDataFrame(input_list, cols)
sparkDF = sparkDF.withColumn('t_date',F.col('t_date').cast('long'))
sparkDF.show()
--- ----------
| id| t_date|
--- ----------
| 1|1635234395|
| 1|1635233361|
--- ----------
來自 Unix 時間
sparkDF.withColumn('t_date_parsed',F.from_unixtime(F.col('t_date'))).show()
--- ---------- -------------------
| id| t_date| t_date_parsed|
--- ---------- -------------------
| 1|1635234395|2021-10-26 13:16:35|
| 1|1635233361|2021-10-26 12:59:21|
--- ---------- -------------------
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/337070.html
上一篇:兩列之間的營業時間
