【发布时间】:2014-01-04 17:17:35
【问题描述】:
我有一个文件,其中的条目看起来像
2013-12-11 23:00:27.003293,$PAMWV,291,R,005.8,M,A*36
2013-12-11 23:00:28.000295,$PAMWV,284,R,005.5,M,A*3F
2013-12-11 23:00:29.000295,$PAMWV,273,R,004.0,M,A*33
2013-12-11 23:00:30.003310,$PAMWV,007,R,004.9,M,A*3B
考虑到分隔符实际上是逗号(','),这是一个经典的 CSV 文件。
我试过了:
wind = loadtxt("/disk2/Wind/ws425.log.test", dtype(str,float), delimiter=',', usecols=(0,4))
ts= time.strptime(str(wind[:,0]), '%Y-%m-%d %H:%M:%S.%f')
我得到的是
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-31-484b71dea724> in <module>()
----> 1 ts= time.strptime(str(wind[:,0]), '%Y-%m-%d %H:%M:%S.%f')
/opt/Enthought/canopy/appdata/canopy-1.0.3.1262.rh5-x86_64/lib/python2.7/_strptime.pyc in _strptime_time(data_string, format)
452
453 def _strptime_time(data_string, format="%a %b %d %H:%M:%S %Y"):
--> 454 return _strptime(data_string, format)[0]
/opt/Enthought/canopy/appdata/canopy-1.0.3.1262.rh5-x86_64/lib/python2.7/_strptime.pyc in _strptime(data_string, format)
323 if not found:
324 raise ValueError("time data %r does not match format %r" %
--> 325 (data_string, format))
326 if len(data_string) != found.end():
327 raise ValueError("unconverted data remains: %s" %
ValueError: time data "['2013-12-12 00:00:02.251311' '2013-12-12 00:00:03.255296'\n '2013-12-12 00:00:04.254294' ..., '2013-12-12 16:10:50.579022'\n '2013-12-12 16:10:51.607035' '2013-12-12 16:10:52.604020']" does not match format '%Y-%m-%d %H:%M:%S.%f'
我怀疑我在 time.strptime() 中误用了数据类型分配,但到目前为止我一直未能找到正确的类型。
建议?
【问题讨论】:
-
为什么不尝试使用csv module?
-
愚蠢的用户回答...我之前没有找到它!让我看看。
-
@TomHeard:
csv会将日期时间字段保留为字符串。 -
@TomHeard:OP 已经使用
time.strptime -
我在部分秒内找不到 %f 字符作为可接受的字符