You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Kotlin Notebook中如何用DataFrame.readCsv解析mm/dd/yyyy格式日期?

解决Kotlin DataFrame 0.15.0读取CSV自定义日期格式的问题

问题场景

使用Kotlin Notebook的DataFrame库0.15.0版本读取Discover卡财务CSV文件时,"Trans. Date"列采用mm/dd/yyyy格式(如12/31/2024),解析时抛出如下异常:

org.jetbrains.kotlinx.dataframe.exceptions.CellConversionException: Failed to convert '12/31/2024' from kotlin.String to kotlinx.datetime.LocalDate in column 'Trans. Date' in column [Trans. Date], row 0
at Cell In[6], line 17

用户已定义对应的DateTimeFormat,但不清楚如何将其传递给CSV解析器。原代码如下:

// import kotlin dataframe library
%use dataframe(v=0.15.0, enableExperimentalCsv=true)

import kotlinx.datetime.format.DateTimeFormat
import kotlinx.datetime.format.char
import kotlinx.datetime.format.Padding.ZERO as ZEROpad

// seems like I need to define the DateTimeFormat,
// but I don't know how to pass it to the CSV parser.
val dateFormat : DateTimeFormat<LocalDate> = LocalDate.Format {
  monthNumber(ZEROpad)
  char('/')
  dayOfMonth(ZEROpad)
  char('/')
  year(ZEROpad)
}

// read the csv file into a dataframe
var discover = DataFrame.readCsv("2024 discover.csv",
  colTypes = mapOf(
    // how do I get this conversion to work for given mm/dd/yyyy format?
    "Trans. Date" to ColType.LocalDate
  )
)

discover.getRows(0..4)

解决方案

在DataFrame 0.15.0的实验性CSV解析模块中,需通过CsvParserSettings配置自定义列转换逻辑,而非仅依赖colTypes参数。具体修改如下:

完整修改代码

%use dataframe(v=0.15.0, enableExperimentalCsv=true)

import kotlinx.datetime.LocalDate
import kotlinx.datetime.format.DateTimeFormat
import kotlinx.datetime.format.char
import kotlinx.datetime.format.Padding.ZERO as ZEROpad
import org.jetbrains.kotlinx.dataframe.io.CsvParserSettings

// 定义目标日期格式
val dateFormat: DateTimeFormat<LocalDate> = LocalDate.Format {
    monthNumber(ZEROpad)
    char('/')
    dayOfMonth(ZEROpad)
    char('/')
    year(ZEROpad)
}

// 配置CSV解析器设置,为指定列注册自定义转换逻辑
val parserSettings = CsvParserSettings().apply {
    convert("Trans. Date") { value ->
        dateFormat.parse(value)
    }
}

// 读取CSV时传入配置好的解析器设置
val discover = DataFrame.readCsv("2024 discover.csv", parserSettings = parserSettings)

discover.getRows(0..4)

关键说明

  • 引入CsvParserSettings:该类用于自定义CSV解析的行为,包括列转换规则
  • 注册自定义转换:通过convert方法指定目标列名,在lambda中使用自定义的dateFormat将字符串解析为LocalDate
  • 传递解析设置:在readCsv方法中添加parserSettings参数,传入配置好的实例

这样就能让解析器按照指定的mm/dd/yyyy格式正确转换"Trans. Date"列的日期字符串。

内容的提问来源于stack exchange,提问作者Travis Well

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 17:25:05