时间戳到字符串转换数据帧
Timestamp to string conversion dataframe
我想在 (scala) spark 数据帧中将时间戳转换为人类可读的字符串并执行以下操作:
df.select(
$"ts",
to_date(from_unixtime($"ts"), "yyyy-MM-dd").as("date"),
to_date(from_unixtime($"ts"), "yyyy-MM-dd-hh").as("date2")
).limit(10)
.show(false)
并得到以下内容:
+----------+----------+-----+
|ts |date |date2|
+----------+----------+-----+
|1605628105|2020-11-17|null |
|1605628105|2020-11-17|null |
|1605628105|2020-11-17|null |
|1605628105|2020-11-17|null |
|1605628105|2020-11-17|null |
|1605628105|2020-11-17|null |
|1605628105|2020-11-17|null |
|1605628105|2020-11-17|null |
|1605628105|2020-11-17|null |
|1605628105|2020-11-17|null |
+----------+----------+-----+
为什么我不能从时间戳中提取小时?为什么它会产生 null?
to_date
只会为您提供日期,而不会提供其他值,例如小时、分钟。要获取小时值,请使用 date_format
函数。
df.select(
$"ts",
to_date(from_unixtime($"ts"), "yyyy-MM-dd").as("date"),
date_format(from_unixtime($"ts"), "yyyy-MM-dd-hh").as("date2") // Added date_format.
)
.limit(10)
.show(false)
我想在 (scala) spark 数据帧中将时间戳转换为人类可读的字符串并执行以下操作:
df.select(
$"ts",
to_date(from_unixtime($"ts"), "yyyy-MM-dd").as("date"),
to_date(from_unixtime($"ts"), "yyyy-MM-dd-hh").as("date2")
).limit(10)
.show(false)
并得到以下内容:
+----------+----------+-----+
|ts |date |date2|
+----------+----------+-----+
|1605628105|2020-11-17|null |
|1605628105|2020-11-17|null |
|1605628105|2020-11-17|null |
|1605628105|2020-11-17|null |
|1605628105|2020-11-17|null |
|1605628105|2020-11-17|null |
|1605628105|2020-11-17|null |
|1605628105|2020-11-17|null |
|1605628105|2020-11-17|null |
|1605628105|2020-11-17|null |
+----------+----------+-----+
为什么我不能从时间戳中提取小时?为什么它会产生 null?
to_date
只会为您提供日期,而不会提供其他值,例如小时、分钟。要获取小时值,请使用 date_format
函数。
df.select(
$"ts",
to_date(from_unixtime($"ts"), "yyyy-MM-dd").as("date"),
date_format(from_unixtime($"ts"), "yyyy-MM-dd-hh").as("date2") // Added date_format.
)
.limit(10)
.show(false)