【问题标题】:pyspark: removing mirosecond from timestamppyspark:从时间戳中删除微秒
【发布时间】:2020-04-30 14:30:15
【问题描述】:

我正在编写一个 pyspark 脚本,其中一项所需的转换是将微秒时间戳转换为秒时间戳 -

  1. 读取 parquet 文件作为输入

  2. 确定是否有任何列是“时间戳”。(以微秒为单位)

    Example - 2019-03-30 19:56:14.520138
    
  3. 如果是,将其转换为 'yyyy-mm-dd hh:mm:ss' 格式

    After conversion - 2019-03-30 19:56:14
    
  4. 将 parquet 格式的数据帧写回 s3。

我已经尝试过,但它不起作用。返回的数据帧仍然显示微秒。

df = spark.read.parquet(p_input_loc)

def customize_df(df):
    getTimestampCol = list(
                filter(lambda x: "timestamp" in x, df.dtypes))
    print(getTimestampCol)
    """[('created_at', 'timestamp'), ('updated_at', 'timestamp')]"""
    if getTimestampCol:
        for row in getTimestampCol:
            df = df.withColumn(row[0], f.to_timestamp(row[0], 'yyyy-mm-dd hh:mm:ss'))
        return df
    else:
        return df

所以我需要帮助!!

【问题讨论】:

    标签: apache-spark pyspark apache-spark-sql pyspark-dataframes


    【解决方案1】:

    这里的问题是你的函数使用。 to_timestamp 函数解析提供的格式中的日期,然后将其转换为时间戳,但要更改格式则需要使用 date_format 函数。

    这是一个例子

    df2 = spark.createDataFrame([("2020-01-01 11:22:59.9989","12312020","31122020"), ("2020-01-01 11:22:59.9989","12312020","31122020" )], ["ID","Start_date","End_date"])
    
    df2.withColumn('ss',f.date_format(df2.ID.cast(t.TimestampType()),'yyyy-MM-dd HH:mm:ss')).select('ss','ID').show(2, False)
    
    +-------------------+------------------------+
    |ss                 |ID                      |
    +-------------------+------------------------+
    |2020-01-01 11:22:59|2020-01-01 11:22:59.9989|
    |2020-01-01 11:22:59|2020-01-01 11:22:59.9989|
    +-------------------+------------------------+
    
    

    所以改变你的

    df = df.withColumn(row[0], f.to_timestamp(row[0], 'yyyy-mm-dd hh:mm:ss'))
    

    df = df.withColumn(row[0], f.date_format(row[0], 'yyyy-MM-dd HH:mm:ss'))
    

    因为您的列已经是 timestampType。

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2019-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-18
      • 1970-01-01
      • 2014-04-07
      相关资源
      最近更新 更多