【问题标题】:Convert string (with timestamp) to timestamp in pyspark将字符串(带时间戳)转换为 pyspark 中的时间戳
【发布时间】:2021-09-28 18:35:11
【问题描述】:

我有一个带有字符串日期时间列的数据框。 我将它转换为时间戳,但值正在改变。 以下是我的代码,谁能帮我在不改变值的情况下进行转换。

df=spark.createDataFrame(
        data = [ ("1","2020-04-06 15:06:16 +00:00")],
        schema=["id","input_timestamp"])
df.printSchema()

#Timestamp String to DateType
df = df.withColumn("timestamp",to_timestamp("input_timestamp")) 
# Using Cast to convert TimestampType to DateType
df.withColumn('timestamp_string', \
         to_timestamp('timestamp').cast('string')) \
  .show(truncate=False)

这是输出:

+---+--------------------------+-------------------+-------------------+
|id |input_timestamp           |timestamp          |timestamp_string   |
+---+--------------------------+-------------------+-------------------+
|1  |2020-04-06 15:06:16 +00:00|2020-04-06 08:06:16|2020-04-06 08:06:16|
+---+--------------------------+-------------------+-------------------+

我想知道为什么时间会从 15 点变为 8 点,我该如何防止呢?

【问题讨论】:

    标签: pyspark timestamp


    【解决方案1】:

    我相信 to_timestamp 正在将时间戳值转换为您的 local time,因为您的数据中有 +00:00。

    • 尝试将格式传递给to_timestamp()函数。

    Example:

    from pyspark.sql.functions import to_timestamp
    
    df.withColumn("timestamp",to_timestamp(col("input_timestamp"),"yyyy-MM-dd HH:mm:ss +00:00")).show(10,False)
    #+---+--------------------------+-------------------+
    #|id |input_timestamp           |timestamp          |
    #+---+--------------------------+-------------------+
    #|1  |2020-04-06 15:06:16 +00:00|2020-04-06 15:06:16|
    #+---+--------------------------+-------------------+
    

    【讨论】:

      【解决方案2】:
      from pyspark.sql.functions import to_utc_timestamp
      
      df = spark.createDataFrame(
          data=[('1', '2020-04-06 15:06:16 +00:00')],
          schema=['id', 'input_timestamp'])
      df.printSchema()
      
      df = df.withColumn('timestamp', to_utc_timestamp('input_timestamp', 
          your_local_timezone))
      df.withColumn('timestamp_string', df.timestamp.cast('string')).show(truncate=False)
      

      将 your_local_timezone 替换为实际值。

      【讨论】:

        猜你喜欢
        • 2020-11-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-28
        • 2020-07-29
        • 1970-01-01
        • 1970-01-01
        • 2021-11-17
        相关资源
        最近更新 更多