【问题标题】:How to convert string date into timestamp in pyspark?如何在pyspark中将字符串日期转换为时间戳?
【发布时间】:2021-09-16 22:24:54
【问题描述】:

我有一个像'06/21/2021 9:27 AM' 这样的日期字符串,我想在 pyspark 中将其转换为时间戳类型。 我和其他人一起尝试过这种方法,但它似乎总是返回 null。

df = df.select(
  from_unixtime(unix_timestamp('date_string', 'MM/dd/yyyy hh:mm:ss a')).cast(TimestampType())
)

有没有人成功地将这种字符串格式转换成时间戳格式?

【问题讨论】:

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


    【解决方案1】:

    06/21/2021 9:27 AM 不包含秒值,因此您应该删除解析器格式中的:ss,请参见以下示例:

    spark.sql("select from_unixtime(unix_timestamp('06/21/2021 9:27 AM', 'MM/dd/yyyy hh:mm a')) ts").show()
    
    +-------------------+
    |                 ts|
    +-------------------+
    |2021-06-21 09:27:00|
    +-------------------+
    

    【讨论】:

      【解决方案2】:

      一种选择是使用带有withColumnto_timestamp 函数的DataFrame API,但在此之前我们需要将timeParserPolicy 设置为LEGACY

      import pyspark.sql.functions as F
      
      spark.sql("set spark.sql.legacy.timeParserPolicy=LEGACY")
      
      df.withColumn('ts', F.to_timestamp('date_string', format='MM/dd/yyyy hh:mm a'))
      

      示例

      df = spark.createDataFrame([
        ('06/21/2021 9:27 AM', ),
        ('06/11/2021 9:02 PM', ),
        ('01/28/2021 12:56 AM', )
      ], ('date_string', ))
      
      df = df.withColumn('ts', F.to_timestamp('date_string', format='MM/dd/yyyy hh:mm a'))
      
      df.show()
      
      +-------------------+-------------------+
      |        date_string|                 ts|
      +-------------------+-------------------+
      | 06/21/2021 9:27 AM|2021-06-21 09:27:00|
      | 06/11/2021 9:02 PM|2021-06-11 21:02:00|
      |01/28/2021 12:56 AM|2021-01-28 00:56:00|
      +-------------------+-------------------+
      

      【讨论】:

        猜你喜欢
        • 2020-09-23
        • 1970-01-01
        • 2011-05-05
        • 1970-01-01
        • 2018-07-28
        • 2011-02-14
        • 2011-05-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多