加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

使用scala将字符串转换为Spark的时间戳

发布时间:2020-12-16 19:21:42 所属栏目:安全 来源:网络整理
导读:我有一个名为train的数据框,他有以下架构: root|-- date_time: string (nullable = true)|-- site_name: integer (nullable = true)|-- posa_continent: integer (nullable = true) 我想将date_timecolumn转换为timestamp并使用从date_timecolumn中提取的ye
我有一个名为train的数据框,他有以下架构:

root
|-- date_time: string (nullable = true)
|-- site_name: integer (nullable = true)
|-- posa_continent: integer (nullable = true)

我想将date_timecolumn转换为timestamp并使用从date_timecolumn中提取的year值创建一个新列.

为了清楚起见,我有以下数据框:

+-------------------+---------+--------------+
|          date_time|site_name|posa_continent|
+-------------------+---------+--------------+
|2014-08-11 07:46:59|        2|             3|
|2014-08-11 08:22:12|        2|             3|
|2015-08-11 08:24:33|        2|             3|
|2016-08-09 18:05:16|        2|             3|
|2011-08-09 18:08:18|        2|             3|
|2009-08-09 18:13:12|        2|             3|
|2014-07-16 09:42:23|        2|             3|
+-------------------+---------+--------------+

我想获得以下数据帧:

+-------------------+---------+--------------+--------+
|          date_time|site_name|posa_continent|year    |
+-------------------+---------+--------------+--------+
|2014-08-11 07:46:59|        2|             3|2014    |
|2014-08-11 08:22:12|        2|             3|2014    |
|2015-08-11 08:24:33|        2|             3|2015    |
|2016-08-09 18:05:16|        2|             3|2016    |
|2011-08-09 18:08:18|        2|             3|2011    |
|2009-08-09 18:13:12|        2|             3|2009    |
|2014-07-16 09:42:23|        2|             3|2014    |
+-------------------+---------+--------------+--------+

解决方法

好吧,如果你想将date_timecolumn转换为timestamp并创建一个带有年份值的新列,那么就这样做:

import org.apache.spark.sql.functions.year

df
  .withColumn("date_time",$"date_time".cast("timestamp"))  // cast to timestamp
  .withColumn("year",year($"date_time"))  // add year column

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读