在Spark数据框中更改列值的日期格式

3

我正在将一个Excel表格读入到Spark 2.0的Dataframe中,然后尝试将一些以MM/DD/YY格式表示日期值的列转换为YYYY-MM-DD格式。这些值是以字符串格式存储的。以下是示例:

+---------------+--------------+
|modified       |      created |
+---------------+--------------+
|           null| 12/4/17 13:45|
|        2/20/18|  2/2/18 20:50|
|        3/20/18|  2/2/18 21:10|
|        2/20/18|  2/2/18 21:23|
|        2/28/18|12/12/17 15:42| 
|        1/25/18| 11/9/17 13:10|
|        1/29/18| 12/6/17 10:07| 
+---------------+--------------+

我希望你能将这个转换为:

+---------------+-----------------+
|modified       |      created    |
+---------------+-----------------+
|           null| 2017-12-04 13:45|
|     2018-02-20| 2018-02-02 20:50|
|     2018-03-20| 2018-02-02 21:10|
|     2018-02-20| 2018-02-02 21:23|
|     2018-02-28| 2017-12-12 15:42| 
|     2018-01-25| 2017-11-09 13:10|
|     2018-01-29| 2017-12-06 10:07| 
+---------------+-----------------+

所以我尝试做:

df.withColumn("modified",date_format(col("modified"),"yyyy-MM-dd"))
  .withColumn("created",to_utc_timestamp(col("created"),"America/New_York"))

但是我的结果中所有的值都是 NULL。我不确定自己错在了哪里。我知道在 created 上使用 to_utc_timestamp 会将整个时间戳转换为 UTC。理想情况下,我希望保持时间不变,只改变日期格式。是否有一种方法可以实现我想做的事情?我该如何纠正错误?

2个回答

9

Spark >= 2.2.0

在Spark中,如果需要使用to_dateto_timestamp两个日期函数,可以使用内置函数进行操作。

import org.apache.spark.sql.functions._
df.withColumn("modified",date_format(to_date(col("modified"), "MM/dd/yy"), "yyyy-MM-dd"))
  .withColumn("created",to_utc_timestamp(to_timestamp(col("created"), "MM/dd/yy HH:mm"), "UTC"))

并且您应该拥有

+----------+-------------------+
|modified  |created            |
+----------+-------------------+
|null      |2017-12-04 13:45:00|
|2018-02-20|2018-02-02 20:50:00|
|2018-03-20|2018-02-02 21:10:00|
|2018-02-20|2018-02-02 21:23:00|
|2018-02-28|2017-12-12 15:42:00|
|2018-01-25|2017-11-09 13:10:00|
|2018-01-29|2017-12-06 10:07:00|
+----------+-------------------+

使用 utc 时区对我来说并没有改变时间

Spark < 2.2.0

import org.apache.spark.sql.functions._
val temp = df.withColumn("modified", from_unixtime(unix_timestamp(col("modified"), "MM/dd/yy"), "yyyy-MM-dd"))
  .withColumn("created", to_utc_timestamp(unix_timestamp(col("created"), "MM/dd/yy HH:mm").cast(TimestampType), "UTC"))

输出的数据框与上面相同。

谢谢你的回答!但是,当我使用 to_date 函数时,它只接受一个参数,参数类型为 column。它不接受模式字符串作为第二个参数。 - Hemanth
1
从2.2.0版本开始可用。 - Ramesh Maharjan
我的Spark版本是2.0。我应该采用不同的方法吗? - Hemanth

2

简单明了:

df.select(
  to_date($"modified", "MM/dd/yy").cast("string").alias("modified"), 
  date_format(to_timestamp($"created", "MM/dd/yy HH:mm"), "yyyy-MM-dd HH:mm").alias("created"))

我正在使用Spark 2.0版本。to_timestamp方法不可用,而to_date方法只接受一个参数。还有其他方法可以使用吗? - Hemanth

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接