簡體   English   中英

將字符串列轉換為特定格式的日期

[英]cast the string column to date for the particular format

如何將字符串列轉換為日期列並在火花數據框中保持相同的格式?

我想通過指定格式將字符串列轉換為日期,但轉換后的日期始終采用默認格式,即 yyyy-MM-dd。

但我想要日期類型的格式為字符串值(我想要數據類型為日期而不是字符串)

例如:

 val spark = SparkSession.builder().master("local").appName("appName").getOrCreate()
 import spark.implicits._
 //here the format is MMddyyyy(For Col2 which is of String type here)
 val df = List(("1","01132019"),("2","01142019")).toDF("Col1","Col2")

 import org.apache.spark.sql.functions._

 //Here i need the Col3 in Date type and with the format MMddyyyy But it is converting into yyyy-MM-dd
  val df1 = df.withColumn("Col3",to_date($"Col2","MMddyyyy"))

 //I tried this but this will give me Col3 in String data type which i need in Date
  val df1 = df.withColumn("Col3",date_format(to_date($"Col2","MMddyyyy"),"MMddyyyy"))

這是不可能的,Spark 只接受日期類型yyyy-MM-dd格式。

如果您需要MMddyyyy這個格式日期字段然后存儲為String類型(如果我們轉換為日期類型結果為 null),在處理時更改格式並轉換為date類型。

前任:

df.withColumn("Col3",$"col2".cast("date")) //casting col2 as date datatype Results null
  .withColumn("col4",to_date($"col2","MMddyyyy").cast("date")) //changing format and casting as date type
  .show(false)

結果:

+----+--------+----+----------+
|Col1|    Col2|Col3|      col4|
+----+--------+----+----------+
|   1|01132019|null|2019-01-13|
|   2|01142019|null|2019-01-14|
+----+--------+----+----------+

Schema:

df.withColumn("Col3",$"col2".cast("date"))
  .withColumn("col4",to_date($"col2","MMddyyyy").cast("date"))
  .printSchema

結果:

root
 |-- Col1: string (nullable = true)
 |-- Col2: string (nullable = true)
 |-- Col3: date (nullable = true)
 |-- col4: date (nullable = true)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM