【问题标题】:create a timestamp from month and year string columns in PySpark从 PySpark 中的月份和年份字符串列创建时间戳
【发布时间】:2019-09-20 19:18:05
【问题描述】:

我想创建一个时间戳列,以从分别包含月份和年份的两列创建折线图。 df 看起来像这样: 我知道我可以创建一个字符串 concat 然后将其转换为日期时间列:

df.select('*', concat('01', df['month'], df['year']).alias('date')).withColumn("date", df['date'].cast(TimestampType()))

但我想要一种使用内置 PySpark 功能的更简洁的方法,该功能还可以帮助我创建其他日期部分,如周数、季度等。有什么建议吗?

【问题讨论】:

    标签: pyspark


    【解决方案1】:

    您必须将字符串连接一次,创建timestamp 类型列,然后您可以轻松提取weekquarter 等。

    您可以使用此功能(并对其进行编辑以创建您需要的任何其他列):

    def spark_date_parsing(df, date_column, date_format):
        """
        Parses the date column given the date format in a spark dataframe
        NOTE: This is a Pyspark implementation
    
        Parameters
        ----------
        :param df: Spark dataframe having a date column
        :param date_column: Name of the date column
        :param date_format: Simple Date Format (Java-style) of the dates in the date column
    
        Returns
        -------
        :return: A spark dataframe with a parsed date column
        """
        df = df.withColumn(date_column, F.to_timestamp(F.col(date_column), date_format))
        # Spark returns 'null' if the parsing fails, so first check the count of null values
        # If parse_fail_count = 0, return parsed column else raise error
        parse_fail_count = df.select(
            ([F.count(F.when(F.col(date_column).isNull(), date_column))])
        ).collect()[0][0]
        if parse_fail_count == 0:
            return df
        else:
            raise ValueError(
                f"Incorrect date format '{date_format}' for date column '{date_column}'"
            )
    
    

    用法(无论您的结果日期格式是什么):

    df = spark_date_parsing(df, "date", "dd/MM/yyyy")

    【讨论】:

      猜你喜欢
      • 2021-12-05
      • 1970-01-01
      • 1970-01-01
      • 2018-10-15
      • 2018-06-20
      • 1970-01-01
      • 2021-08-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多