【问题标题】:Converting Epoch Seconds to timestamp using Pyspark使用 Pyspark 将纪元秒转换为时间戳
【发布时间】:2021-12-11 14:49:24
【问题描述】:

我有一个如下数据集:

+---+----------+
|id |t_date    |
+---+----------+
|1  |1635234395|
|1  |1635233361|
+---+----------+  

其中t_date 包含今天日期的epoch 秒。现在,我想将其转换为时间戳。我尝试了以下代码,但输出错误:

我参考了以下两个链接,但没有运气:

  1. How do I convert column of unix epoch to Date in Apache spark DataFrame using Java?
  2. Converting epoch to datetime in PySpark data frame using udf

【问题讨论】:

  • 为什么要除以 1000 ? from_unixtime 需要几秒钟作为输入,您似乎已经拥有了

标签: apache-spark datetime pyspark


【解决方案1】:

您不必除以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|
+---+----------+-------------------+

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-24
    • 1970-01-01
    • 2021-03-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多