csv - GOCSV 映射到带有日期/时间的结构:字段为空时的问题
问题描述
编辑:我犯了一个错误并纠正了它
我正在尝试将CSV
文件映射到定义字段的结构time.Datetime
(稍后我想将日期时间格式更改为另一种格式)。
这是我的程序的输出
❯ go run issue.go ✗ master
record: 05/02/2019 15:02:31
record: 05/02/2019 16:02:40
record:
record on line 0; parse error on line 4, column 2: parsing time "" as "02/01/2006 15:04:05": cannot parse "" as "02"
1936 - 2019-02-05 15:02:31 +0000 UTC
1937 - 2019-02-05 16:02:40 +0000 UTC
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x8 pc=0x10e58cc]
goroutine 1 [running]:
main.main()
/Users/gtheys/Code/go/src/github.axa.com/KTAXA/claims-headers-poc/issue.go:49 +0x1bc
exit status 2
我尝试time.Parse
使用空字符串执行,它不起作用。所以问题应该出在这里。但我不知道如何在以下代码中优雅地处理它:
package main
import (
"encoding/csv"
"fmt"
"io"
"os"
"time"
"github.com/gocarina/gocsv"
)
type DateTime struct {
time.Time
}
type Issue struct {
NotifyNo string
NotifyDate DateTime
}
// Convert the CSV string as internal date
func (date *DateTime) UnmarshalCSV(csv string) (err error) {
fmt.Println("record: ", csv)
date.Time, err = time.Parse("02/01/2006 15:04:05", csv)
return err
}
func main() {
//const layout = "02/05/2006 15:04:00"
issuesFile, err := os.OpenFile("ISSUES.txt", os.O_RDWR|os.O_CREATE, os.ModePerm)
if err != nil {
panic(err)
}
defer issuesFile.Close()
issues := []*Issue{}
gocsv.SetCSVReader(func(in io.Reader) gocsv.CSVReader {
r := csv.NewReader(in)
r.Comma = '|'
return r // Allows use pipe as delimiter
})
if err := gocsv.UnmarshalFile(issuesFile, &issues); err != nil {
fmt.Println(err)
}
for _, issue := range issues {
fmt.Println(issue.NotifyNo, " - ", issue.NotifyDate)
}
if _, err := issuesFile.Seek(0, 0); err != nil { // Go to the start of the file
panic(err)
}
}
csv输入文件:
NotifyNo|NotifyDate|
1936|05/02/2019 15:02:31|
1937|05/02/2019 16:02:40|
1938||
1951|05/02/2019 17:02:19|
解决方案
推荐阅读
- sql - 源查询中的 ssis oledb 源死锁
- firebase - 如何在 Cloud FireStore 的 TextFormField 中提供 initialValue
- google-apps-script - 从具有多列的电子表格中提取时,限制下拉列表中的结果数量
- python - 当 API 返回新结果时调用函数
- apache-spark - 带参数的默认 Spark 侦听器
- javascript - instanceof 在打字稿/角度项目之间没有按预期工作
- python - 我的 Tetration(复数)函数必须更好地矢量化(Python)
- mysql - 如何从 MySQL 中的电话号码中删除空格
- java - 我正在寻找一个 java 正则表达式,如果字符串包含任何字符超过 3 次,它将返回 true
- powershell - 检查每天是否存在超过 1 个刷新计划重复