spark编程04——关于数据清洗中的各种常见时间格式转换

一.时间戳转化为日期格式:

 val time="1622457251089"
    //TODO 时间转换函数:时间戳 1622457251089
    def replaceTime1(tm:String) :String= {
      import java.text.SimpleDateFormat
      val sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
      val format: String = sf.format(new Date(Long.parseLong(time)))
      format
    }
    println("转化后的时间是:"+replaceTime1(time))

 二.带时区的格式:2021-04-27T11:34:52+08:00

import org.apache.spark.sql.functions.udf
 
//TODO 时间格式转换函数 2021-04-27T11:34:52+08:00
    def replaceTime1(tm:String) :String= {
      val t1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX")
      val t2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
      val t: Date =t1.parse(tm)
      val newtime=t2.format(t)
      newtime
    }
 spark.udf.register("replaceTime1",replaceTime1(_:String))//需要注册一下
 val addCol_replacegTime1 = udf(replaceTime1 _)
 val dfewm03=dfewm02.withColumn("inTime",addCol_replacegTime1(dfewm02("intime")))

三.类时间格式:20210703105537

import org.apache.spark.sql.functions.udf

 //TODO 时间转换函数:20210703105537
    def replaceTime2(time:String):String={
      val time1=new SimpleDateFormat("yyyyMMddHHmmss")
      val time2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
      val t: Date =time1.parse(time)
      val newtime=time2.format(t)
      newtime
    }

 spark.udf register("replaceTime2", replaceTime2(_: String))//注册
 val addCol_replacegTime2 = udf(replaceTime2 _)
 val dfewm04=dfewm03.withColumn("payTime2",addCol_replacegTime2(dfewm03("payTime")))

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值