【问题标题】:Pyspark: Convert Column from String Numbers to Timestamp TypePyspark:将列从字符串数字转换为时间戳类型
【发布时间】:2021-12-01 00:43:07
【问题描述】:

我希望将字符串格式的数字转换为时间戳。

示例:

+--------+-------------------+
|date_str|expected date      |
+--------+-------------------+
|1.63E+15|1991-11-25 13:39:00|
|1.63E+15|1991-11-25 13:40:00|
|1.63E+15|1991-11-25 13:41:00|
+--------+-------------------+

我尝试使用 to_timestamp() 但返回 Null 值。也转换为unix_timestamp,但没有运气。

sdf1.select(F.to_timestamp(sdf1.date_str, 'yyyy/MM/dd HH:mm:ss').alias('date')).show()
sdf1.select(to_timestamp('date_str', 'dd/MM/yyyy HH:mm:ss')).show()

【问题讨论】:

  • 你的电话号码是多少?你确定它是一个字符串吗?导致“1.63E+15”与字符串中的“163000000000”不同...
  • 它是字符串...我已经检查了架构
  • 好吧,如果是字符串,那么每一行的时间戳怎么会不同呢?相同的输入=相同的输出。你的例子有问题
  • 日期列是我在转换后所期望的
  • 但是你知道同样的输入产生同样的输出吗?转换时没有魔法......我们无法恢复丢失的数字。

标签: python dataframe apache-spark pyspark


【解决方案1】:

首先,您要求的转换是不可能的。相同的输入不能产生不同的输出。应该是:

+--------+-------------------+
|date_str|expected date      |
+--------+-------------------+
|1.63E+15|1991-11-25 13:39:00|  # Same "expected date" at each line
|1.63E+15|1991-11-25 13:39:00|
|1.63E+15|1991-11-25 13:39:00|
+--------+-------------------+

那么,您需要的函数可能是from_unixtime - 将数字格式的时间戳转换为字符串/时间戳格式的时间戳:

time_df = spark.createDataFrame([(1428476400,)], ['unix_time'])

time_df.select(from_unixtime('unix_time').alias('ts')).collect()
# [Row(ts='2015-04-08 00:00:00')]

唯一的问题是,在您的示例中,您的数字长度为 16 位 (E+15),这对于 unix 时间戳而言过于精确。您可能应该将其除以 1000000。

from pyspark.sql import functions as F, types as T

df.withColumn(
    "date_num", F.col("date_str").cast(T.DecimalType(16, 0)) / 1000000
).withColumn(
    "date", F.from_unixtime("date_num")
).show()
+--------+-------------------+-------------------+
|date_str|           date_num|               date|
+--------+-------------------+-------------------+
|1.63E+15|1630000000.00000000|2021-08-26 17:46:40|
+--------+-------------------+-------------------+

【讨论】:

  • 这里的“T”是什么?
  • @martian_rover 导入丢失,抱歉!
  • 架构中的数据类型仍然是字符串,而不是“日期”列的时间戳
  • @martian_rover 只是投射它:F.from_unixtime("date_num").cast("timestamp")
  • 它为所有行返回相同的时间戳
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-19
  • 2021-11-17
  • 1970-01-01
  • 1970-01-01
  • 2021-06-28
  • 2021-07-24
相关资源
最近更新 更多