【问题标题】:Parsing timestamps from string and rounding seconds in spark从字符串解析时间戳并在火花中舍入秒
【发布时间】:2019-07-16 15:48:28
【问题描述】:

我有一个带有 "requestTime" 列的 spark DataFrame,它是时间戳的字符串表示形式。如何将其转换为这种格式:YY-MM-DD HH:MM:SS,知道我有以下值:20171107014824952(这意味着:2017-11-07 01:48:25)?

专用于秒的部分由 5 位数字组成,在上面的示例中,秒部分是 = 24952,而日志文件中显示的是 25,所以我必须在应用 @ 之前四舍五入 24.952 987654330@函数,这就是我寻求帮助的原因。

【问题讨论】:

  • 不,这不是同一个问题,这里我有一个非常不同的时间格式。无论如何谢谢@pault
  • 如果您阅读链接副本上的答案,您将看到可以指定格式。
  • 如果你检查了我的专栏的格式,你会发现专门用于秒的部分是由5位数字组成的,在上面的例子中,秒部分是= 24952,显示在日志文件是 25,所以我必须在应用“to_timestamp”函数之前四舍五入 24.952,这就是我寻求帮助的原因
  • 将来,添加您尝试过的方法以及为什么它在问题中不起作用的详细信息会很有帮助。我已经为你编辑了这些问题。请阅读How to Askhow to create good reproducible spark dataframe examples

标签: apache-spark pyspark timestamp


【解决方案1】:

假设你有以下 spark DataFrame:

df.show()
#+-----------------+
#|      requestTime|
#+-----------------+
#|20171107014824952|
#+-----------------+

使用架构:

df.printSchema()
#root
# |-- requestTime: string (nullable = true)

您可以使用Convert pyspark string to date format 中描述的技术将其转换为时间戳。由于解决方案取决于您的 spark 版本,因此我创建了以下辅助函数:

import pyspark.sql.functions as f

def timestamp_from_string(date_str, fmt):
    try:
        """For spark version 2.2 and above, to_timestamp is available"""
        return f.to_timestamp(date_str, fmt)
    except (TypeError, AttributeError):
        """For spark version 2.1 and below, you'll have to do it this way"""
        return f.from_unixtime(f.unix_timestamp(date_str, fmt))

现在使用适当的格式在您的数据上调用它:

df.withColumn(
    "requestTime", 
    timestamp_from_string(f.col("requestTime"), "yyyyMMddhhmmssSSS")
).show()
#+-------------------+
#|        requestTime|
#+-------------------+
#|2017-11-07 01:48:24|
#+-------------------+

不幸的是,这个truncates the timestamp instead of rounding

因此,您需要在转换之前自己进行舍入。棘手的部分是数字存储为字符串 - 您必须将其转换为double,除以1000.,将其转换回long(去掉小数点,你可以' t 使用int,因为数字太大),最后回到字符串。

df.withColumn(
    "requestTime",
    timestamp_from_string(
        f.round(f.col("requestTime").cast("double")/1000.0).cast('long').cast('string'),
        "yyyyMMddhhmmss"
    )
).show()
#+-------------------+
#|        requestTime|
#+-------------------+
#|2017-11-07 01:48:25|
#+-------------------+

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-10
    • 2012-10-28
    • 2015-04-02
    • 1970-01-01
    • 2019-10-30
    • 1970-01-01
    相关资源
    最近更新 更多