pyspark - 以天为单位触发 sql datediff
问题描述
我正在尝试从表中计算 current_timestamp() 和 max(timestamp_field) 之间的天数。
maxModifiedDate = spark.sql("select date_format(max(lastmodifieddate), 'MM/dd/yyyy hh:mm:ss') as maxModifiedDate,date_format(current_timestamp(),'MM/dd/yyyy hh:mm:ss') as CurrentTimeStamp, datediff(current_timestamp(), date_format(max(lastmodifieddate), 'MM/dd/yyyy hh:mm:ss')) as daysDiff from db.tbl")
但我在 daysDiff 中得到了空值。为什么会这样,我该如何解决?
------------------+-------------------+--------+
| maxModifiedDate| CurrentTimeStamp|daysDiff|
+-------------------+-------------------+--------+
|01/29/2020 05:07:51|06/29/2020 08:36:28| null|
+-------------------+-------------------+--------+
解决方案
检查一下:我曾经to_timestamp
转换为日期格式并使用datediff
函数来计算时间差。
from pyspark.sql import functions as F
# InputDF
# +-------------------+-------------------+
# | maxModifiedDate| CurrentTimeStamp|
# +-------------------+-------------------+
# |01/29/2020 05:07:51|06/29/2020 08:36:28|
# +-------------------+-------------------+
df.select("maxModifiedDate","CurrentTimeStamp",F.datediff( F.to_timestamp("CurrentTimeStamp", format= 'MM/dd/yyyy'), F.to_timestamp("maxModifiedDate", format= 'MM/dd/yyyy')).alias("datediff")).show()
# +-------------------+-------------------+--------+
# | maxModifiedDate| CurrentTimeStamp|datediff|
# +-------------------+-------------------+--------+
# |01/29/2020 05:07:51|06/29/2020 08:36:28| 152|
# +-------------------+-------------------+--------+
使用sparksql
spark.sql("select maxModifiedDate,CurrentTimeStamp, datediff(to_timestamp(CurrentTimeStamp, 'MM/dd/yyyy'), to_timestamp(maxModifiedDate, 'MM/dd/yyyy')) as datediff from table ").show()
推荐阅读
- javascript - 根据用户事件在 Firebase 托管中自动创建新页面(JAVASCRIPT)
- php - 为什么我的 echo json_encode($data) 实际上会在我的页面上显示某些内容以及如何避免这种情况(ajax/php 表单验证)
- typescript - NestJs - DTO 和实体
- schema.org - JobPosting 架构问题:数字不是 baseSalary 属性的已知有效目标类型
- tensorflow - 无法在 Keras 中导入 AttentionLayer (TF1.13)
- cmake - 如何在 GNU make 的 cmake 中包含由自定义命令生成的依赖文件?
- python - 无法使用 Pipenv 缓存对 Github Actions 的依赖项
- c# - 以编程方式添加到 DataGridView 单元格的 ComboBox 未在单元格单击时展开
- ruby - 为 Ruby 和 Rails 配置 OpenLiteSpeed
- java - 浏览矩阵 / Lee 算法