apache-spark - 来自多列的 Pyspark 日期格式
问题描述
我的数据框中有四个字符串列'hour', 'day', 'month', 'year'
。我想以格式创建新列 fulldate 'dd/MM/yyyy HH:mm'
。
df2 = df1.withColumn("fulldate", to_date(concat(col('day'), lit('/'), col('month'), lit('/'), col('year'), lit(' '), col('hour'), lit(':'), lit('0'), lit('0')), 'dd/MM/yyyy HH:mm'))
但它似乎不起作用。我得到格式“yyyy-mm-dd”。
我错过了什么吗?
解决方案
使用date_format
而不是to_date
.
to_date
将列从给定格式转换为日期类型,同时date_format
将日期类型列转换为给定格式。
from pyspark.sql.functions import date_format, concat, col, lit
df2 = df1.withColumn(
"fulldate",
date_format(
concat(col('year'), lit('/'), col('month'), lit('/'), col('day'), lit(' '), col('hour'), lit(':'), lit('00'), lit(':'), lit('00')),
'dd/MM/yyyy HH:mm'
)
)
为了更好的可读性,您可以使用format_string
:
from pyspark.sql.functions import date_format, format_string, col
df2 = df1.withColumn(
"fulldate",
date_format(
format_string('%d/%d/%d %d:00:00', col('year'), col('month'), col('day'), col('hour')),
'dd/MM/yyyy HH:mm'
)
)
推荐阅读
- javascript - JavaScript:如何从内部函数调用 Bootstrap 模态?
- android - Android 布局未按预期运行
- html - css 垂直按钮组 - 忽略 justify-content
- ruby - Aws::S3::Errors::InvalidArgument (): on bucket.put_object
- javascript - 如何永久修复博客上的小部件脚本
- rust - 带有 eq_any 的子查询无法编译
- python - 按日期对 Pandas 数据框列索引进行排序
- c++ - 带有方法和静态实例的 C++11 枚举的成语?
- x86 - 是否可以制造支持多个 ISA 的处理器?(例如:ARM + x86)
- locust - Locust 安装:psutil 编译失败,退出状态为 1 Python.h:没有这样的文件或目录