簡體   English   中英

如何更改 Spark 中的日期格式?

[英]How to change date format in Spark?

我有以下數據幀:

+----------+-------------------+
| timestamp|            created|
+----------+-------------------+
|1519858893|2018-03-01 00:01:33|
|1519858950|2018-03-01 00:02:30|
|1519859900|2018-03-01 00:18:20|
|1519859900|2018-03-01 00:18:20|

如何正確創建時間戳`?

我能夠創建timestamp列,它是紀元時間戳,但日期不一致:

df.withColumn("timestamp",unix_timestamp($"created"))

例如, 1519858893點至2018-02-28

只需使用date_formatto_utc_timestamp內置函數

import org.apache.spark.sql.functions._
df.withColumn("timestamp", to_utc_timestamp(date_format(col("created"), "yyy-MM-dd"), "Asia/Kathmandu"))

試試下面的代碼

df.withColumn("dateColumn", df("timestamp").cast(DateType))

您可以在此處查看一個解決方案https://stackoverflow.com/a/46595413要詳細說明具有不同格式的時間戳/日期字符串的數據幀,您可以這樣做 -

val df = spark.sparkContext.parallelize(Seq("2020-04-21 10:43:12.000Z", "20-04-2019 10:34:12", "11-30-2019 10:34:12", "2020-05-21 21:32:43", "20-04-2019", "2020-04-21")).toDF("ts")

def strToDate(col: Column): Column = {
    val formats: Seq[String] = Seq("dd-MM-yyyy HH:mm:SS", "yyyy-MM-dd HH:mm:SS", "dd-MM-yyyy", "yyyy-MM-dd")
    coalesce(formats.map(f => to_timestamp(col, f).cast(DateType)): _*)
  }

val formattedDF = df.withColumn("dt", strToDate(df.col("ts")))

formattedDF.show()
+--------------------+----------+
|                  ts|        dt|
+--------------------+----------+
|2020-04-21 10:43:...|2020-04-21|
| 20-04-2019 10:34:12|2019-04-20|
| 2020-05-21 21:32:43|2020-05-21|
|          20-04-2019|2019-04-20|
|          2020-04-21|2020-04-21|
+--------------------+----------+

注意: - 此代碼假設數據不包含任何格式列 -> MM-dd-yyyy, MM-dd-yyyy HH:mm:SS

暫無
暫無

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

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