Код: Выделить всё
datdoc
07-SEP-24
07-SEP-2024
07-SEP-2024
07-SEP-2024
07-SEP-24
07-SEP-24
07-SEP-2024
07-SEP-2024
07-SEP-2024
07-SEP-2024
07-SEP-2024
- Первая попытка: использование CASE WHEN
Для обработки нескольких форматов дат я использовал следующую полезную нагрузку:
Код: Выделить всё
columns = {'field_name': 'datdoc', 'current_format': ['dd-MMM-yy', 'dd-MMM-yyyy'], 'data_type': 'Date'}
dateexpression = Column
- Вторая попытка: анализ одного формата
Я также пробовал упростить до один формат:
Код: Выделить всё
columns = {'field_name': 'datdoc', 'current_format': ['dd-MMM-yy'], 'data_type': 'Date'}
date_expression = Column
Код: Выделить всё
def change_date_format(self, columns) -> None:
def _convert_date_format(field_name: str, current_format: list, is_timestamp: bool) -> F.Column:
base_function = F.to_timestamp if is_timestamp else F.to_date
expression = None
if len(current_format) == 1:
return base_function(F.col(field_name), current_format[0]).alias(field_name)
else:
for fmt in current_format:
current_expr = base_function(F.col(field_name), fmt)
if expression is None:
expression = F.when(current_expr.isNotNull(), current_expr)
else:
expression = expression.when(current_expr.isNotNull(), current_expr)
return expression.otherwise(F.lit(None)).alias(field_name)
cols = {col["field_name"] for col in columns}
date_expressions = []
for col in columns:
if col["data_type"] in ["DateTime", "Time"]:
date_expressions.append(_convert_date_format(col["field_name"], col["current_format"], True))
elif col["data_type"] == "Date":
date_expressions.append(_convert_date_format(col["field_name"], col["current_format"], False))
expression = [F.col(i) for i in self.df.columns if i not in cols]
self.df = self.df.select(*date_expressions, *expression)
Код: Выделить всё
24/09/25 21:10:18 WARN TaskSetManager: Lost task 0.0 in stage 9.0 (TID 7) (rhy-4 executor driver): org.apache.spark.SparkUpgradeException: [INCONSISTENT_BEHAVIOR_CROSS_VERSION.PARSE_DATETIME_BY_NEW_PARSER] You may get a different result due to the upgrading to Spark >= 3.0:
Fail to parse '07-SEP-2024' in the new parser. You can set "spark.sql.legacy.timeParserPolicy" to "LEGACY" to restore the behavior before Spark 3.0, or set to "CORRECTED" and treat it as an invalid datetime string.
Вопрос
Есть ли способ гарантировать, что недопустимые строки даты возвращаются как NULL вместо неправильного анализа? Один из рассмотренных мной подходов — использование CASE WHEN с шаблоном RegEx в PySpark. Однако сначала я хотел бы изучить возможность исправления моего текущего подхода. Будем очень признательны за любые рекомендации о том, как этого добиться!
Подробнее здесь: https://stackoverflow.com/questions/790 ... th-pyspark