【问题标题】:Pyspark: Difference between two Dates (Cast TimestampType, Datediff)Pyspark:两个日期之间的差异(Cast TimestampType,Datediff)
【发布时间】:2017-06-29 09:24:44
【问题描述】:

有一个包含事件和特定时间戳的表格。我很难计算使用 Pyspark 2.0 API 过去的天数。当时间戳遵循另一种格式(yyyy-mm-dd)时,我设法做同样的事情

    +-------------------+------------------------+----------+--------------+
     | first_booking_date|first_booking_date_clean|  today   |customer_since|
    +-------------------+------------------------+----------+--------------+
     |02-06-2011 20:52:04|              02-06-2011|02-06-2011|          null|
     |03-06-2004 18:15:10|              03-06-2004|02-06-2011|          null|

我尝试了以下方法(没有任何效果): - 使用字符串操作提取日期并使用 datediff - 转换为时间戳,然后提取 dd:MM:yy (->result null) - 我更喜欢使用 pyspark 命令而不是使用 sql 进行任何其他转换

非常感谢您的帮助,最好的,非常感谢!!!

编辑:这是一个不起作用的示例:

import datetime
today = datetime.date(2011,2,1)
today = "02-06-2011"
first_bookings = first_bookings.withColumn("today",F.lit(today))
first_bookings = first_bookings.withColumn("first_booking_date_clean",F.substring(first_bookings.first_booking_date, 0, 10))
first_bookings = first_bookings.withColumn("customer_since",F.datediff(first_bookings.today,first_bookings.first_booking_date_clean))

【问题讨论】:

标签: timestamp pyspark datediff


【解决方案1】:

这个答案基本上是https://stackoverflow.com/a/36985244/4219202的副本 在您的情况下,first_booking_date_cleantoday

列的 timeFmt 将是“dd-MM-yyyy”

从 Spark 1.5 开始,您可以使用 unix_timestamp:

from pyspark.sql import functions as F
timeFmt = "yyyy-MM-dd'T'HH:mm:ss.SSS"
timeDiff = (F.unix_timestamp('EndDateTime', format=timeFmt)
            - F.unix_timestamp('StartDateTime', format=timeFmt))
df = df.withColumn("Duration", timeDiff)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-23
    • 2011-10-29
    • 1970-01-01
    • 2014-02-12
    • 2015-09-14
    • 2015-06-21
    • 2020-02-06
    • 2023-04-08
    相关资源
    最近更新 更多