excel - Spark(Scala)解析时间戳格式为 ("dd-MMM-yy hh:mm:ss:SSSSSSSSS aa"的字段的问题)

标签 excel scala apache-spark datetime apache-spark-sql

我想解析一个Excel文件。 该文件有几个字段值作为时间戳格式 ("dd-MMM-yy hh:mm:ss:SSSSSSSSS aa") 我已将字段类型定义为时间戳,但我的应用程序无法识别数据类型并且无法加载数据,但如果我使用 StringType 作为数据类型,那么它能够解析文件,但我不想使用这种替代方法。 因此寻找正确的解决方案。 我的代码如下:

ReadExcel("C:path\to\the\raw_file\Consignments.xlsx", "A1", MySchema, spark,  "dd-MM-yyyy", "dd-MMM-yy hh:mm:ss:SSSSSSSSS aa")


def ReadExcel(path: String, dataAddress: String = "A2", Schema: StructType, spark: org.apache.spark.sql.SparkSession, datefmt: String = "dd-MM-yyyy", tsfmt: String = "dd-MM-yyyy HH:mm:ss"): DataFrame = {

    /**
     * Though Crealytics accept TimestampFormat Only
     * You can Create CustomSchema with DateType and Date values in data will be typed to Date
     */

    cleanHeaders(spark.read
      .format("com.crealytics.spark.excel")
      .option("dataAddress", dataAddress) //
      .option("useHeader", "false") // Required
      .option("treatEmptyValuesAsNulls", "true") // Optional, default: true
      .option("inferSchema", "false") // Optional, default: false
      .option("addColorColumns", "false") // Optional, default: false
      .option("timestampFormat", "dd-MM-yyyy HH:mm:ss") // Optional, default: yyyy-mm-dd hh:mm:ss[.fffffffff]
      //.option("maxRowsInMemory", 20) // Optional, default None. If set, uses a streaming reader which can help with big files
      //.option("excerptSize", 10) // Optional, default: 10. If set and if schema inferred, number of rows to infer schema from
      .schema(Schema)
      .load(path))
}

示例日期数据:24-SEP-19 07.17.20.873000000 AM 请注意:我正在使用 Databricks 笔记本和 crealytics 库来读取 Excel 文件。

最佳答案

@维纳斯。我认为时间戳表示是不正确的。 873000000毫秒换算成天数就超过10天了。我认为你只需要考虑毫秒的前 3 位数字。请检查。

如果是这种情况,您可以遵循以下方法:

  1. 首先读取文件,使用子字符串来剪切时间戳列的前 3 位毫秒部分。
  2. 然后使用 Spark 转换,通常在方法 withColumn 中使用,然后使用 from_unixtime(unix_time(column, 'timestamp format'), 'format')

关于excel - Spark(Scala)解析时间戳格式为 ("dd-MMM-yy hh:mm:ss:SSSSSSSSS aa"的字段的问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58242102/

相关文章:

excel - 在单元格中创建重击效果

python - 如何在 pyspark 列表达式中引用名称中带有连字符的列?

excel - 两列的输出差异具有排除标准

excel - VBA 循环和 if 语句问题

r - 使用VBA在excel中融化/ reshape ?

scala - 从 Scala String 到 java.lang.String 的转换

scala-library 导入了两次?

json - 如何通过 Circe 修改 json 的值类型

scala - 相同的行为 Scala Spark Sample 和 SampleBy

apache-spark - 基于两个或多个列的 Spark DataFrame 聚合