如何从csv文件中获取日期时间和时间的数据类型:
with open(dataPath, newline='') as csvData:
reader = csv.DictReader(csvData, delimiter=';')
head = next(reader)
.
.我有以下csv文件:
"...."; "YEAR"; "TIME"; "..." --> head
"...."; "19.05.2020"; "0050"; "..." --> "0050" means 00:50
"...."; "12.05.2020"; "2035"; "..." --> "2035" means 20:35我用一个函数尝试了一下:
def convert(value):
heuristics = [lambda value: datetime.strptime(value, "%d.%m.%Y"), datetime.strptime(value, "%H%D"), int, float]
for type in heuristics:
try:
return type(value)
except ValueError:
continue
# All other heuristics failed it is a string
return value如果我有一个值"1,2,3“,它会输出一个值error,但为此我写了除了ValueError: continue,为什么当这个错误发生时,它不继续,和"513165”一样
谢谢
发布于 2020-11-06 00:30:24
如果你想让它正常工作,有几件事:
strptime operations
%D不是有效的strptime指令,我假设您的意思是重新定义内置的type
上发生了什么
使用一些测试的工作示例(但不要假设所有可能的错误都会被完全覆盖...)
def convert(value):
heuristics = [lambda value: datetime.strptime(value, "%d.%m.%Y"),
lambda value: datetime.strptime(value, "%H%M"),
int,
float]
for f in heuristics:
try:
return f(value)
except ValueError as e:
print(f"encountered error: {e}")
continue
# All other heuristics failed it is a string
return value
for v in ('2355', 'asdf', '12', '3.14', '7.12.2013'):
print(f"testing '{v}'...")
result = convert(v)
print(result, type(result))给你
testing '2355'...
encountered error: time data '2355' does not match format '%d.%m.%Y'
1900-01-01 23:55:00 <class 'datetime.datetime'>
testing 'asdf'...
encountered error: time data 'asdf' does not match format '%d.%m.%Y'
encountered error: time data 'asdf' does not match format '%H%M'
encountered error: invalid literal for int() with base 10: 'asdf'
encountered error: could not convert string to float: 'asdf'
asdf <class 'str'>
testing '12'...
encountered error: time data '12' does not match format '%d.%m.%Y'
1900-01-01 01:02:00 <class 'datetime.datetime'>
testing '3.14'...
encountered error: time data '3.14' does not match format '%d.%m.%Y'
encountered error: time data '3.14' does not match format '%H%M'
encountered error: invalid literal for int() with base 10: '3.14'
3.14 <class 'float'>
testing '7.12.2013'...
2013-12-07 00:00:00 <class 'datetime.datetime'>https://stackoverflow.com/questions/64699652
复制相似问题