为了账号安全,请及时绑定邮箱和手机立即绑定

从字符串 PySpark 中获取年、月、日

从字符串 PySpark 中获取年、月、日

动漫人物 2023-12-05 15:53:17
我需要Year, Month, Day, Hour从 Spark df 中的列中获取字符串Time。我还需要将这些值保存在单独的列中。数据如下:ID               Time111            2020-03-23-12:40:04112            2020-04-23-12:40:04113            2020-05-23-12:40:04期望的输出是:ID        Year        Month        Day111     2020         03            23112     2020         04            23113     2020         05            23我试过:data_df.select(    year("Time").alias('year'),     month("Time").alias('month'),     dayofmonth("Time").alias('day')).show()它返回所有 Null 值。
查看完整描述

1 回答

?
UYOU

TA贡献1878条经验 获得超4个赞

我假设该Time列是一个字符串。您可以使用正则表达式提取所需的值,但这会非常痛苦。另一种选择是将字符串转换为时间戳,然后使用函数等year。month


另外,您的时间戳不是标准格式,因此您需要指定它。


data = [(111, '2020-03-23-12:40:04'),

        (112, '2020-04-23-12:40:04'),

        (113, '2020-05-23-12:40:04')]

df = spark.createDataFrame(data, ['ID', 'Time'])


df\

    .withColumn('t', F.to_timestamp('Time', 'yyyy-MM-dd-HH:mm:ss'))\

    .select('ID',

            F.year('t').alias('year'),

            F.month('t').alias('month'),

            F.dayofmonth('t').alias('day'),

            F.hour('t').alias('hour')

    ).show()

产生:


+---+----+-----+---+----+

| ID|year|month|day|hour|

+---+----+-----+---+----+

|111|2020|    3| 23|  12|

|112|2020|    4| 23|  12|

|113|2020|    5| 23|  12|

+---+----+-----+---+----+



查看完整回答
反对 回复 2023-12-05
  • 1 回答
  • 0 关注
  • 57 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信