Hem*_*nth 1 scala dataframe apache-spark apache-spark-sql
我正在将Excel工作表读入Dataframe
Spark 2.0中,然后尝试将具有日期值的某些列MM/DD/YY
转换为YYYY-MM-DD
format格式。值是字符串格式。下面是示例:
+---------------+--------------+
|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|
+---------------+--------------+
Run Code Online (Sandbox Code Playgroud)
我希望将其转换为:
+---------------+-----------------+
|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|
+---------------+-----------------+
Run Code Online (Sandbox Code Playgroud)
所以我试着做:
df.withColumn("modified",date_format(col("modified"),"yyyy-MM-dd"))
.withColumn("created",to_utc_timestamp(col("created"),"America/New_York"))
Run Code Online (Sandbox Code Playgroud)
但这给NULL
了我结果所有的价值。我不确定我要去哪里错。我知道to_utc_timestamp
on created
会将整个时间戳转换为UTC。理想情况下,我想保持时间不变,只更改日期格式。有没有办法实现我想做的事情?我哪里出问题了?
任何帮助,将不胜感激。谢谢。
您需要以下附加功能to_date
和to_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"))
Run Code Online (Sandbox Code Playgroud)
你应该有
+----------+-------------------+
|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|
+----------+-------------------+
Run Code Online (Sandbox Code Playgroud)
使用utc
时区不会改变我的时间
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"))
Run Code Online (Sandbox Code Playgroud)
输出数据帧与上面相同
归档时间: |
|
查看次数: |
7055 次 |
最近记录: |