pyspark 将某种数据类型的所有列转换为另一种

pyspark cast all columns of a certain data type to another

我有一个包含一定数量日期列的数据框。我想将它们全部转换为时间戳,而不必担心列的确切名称。所以我想要的是符合以下内容的内容:"Cast all date columns to timestamp and keep the same column names"

我知道有一个专栏是:

df = df.withColumn('DATUM', df['DATUM'].cast('timestamp'))

您可以使用 for 循环,并转换为时间戳

df.select(
    *[df[col_name].cast('timestamp') for col_name in df.columns]
)

您可以使用循环检测类型何时为 date 并仅对这些情况执行转换。

for col in df.dtypes:
  if(col[1] == 'date'):
    df = df.withColumn(col[0],df[col[0]].cast('timestamp'))