将文本文件中的日期列转换为浮点 [英] convert date column in a text file to float

查看:77
本文介绍了将文本文件中的日期列转换为浮点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据文件,该文件的第二列是日期,格式为"01/01/2007".我试图将此列转换为数字格式,以便可以将文本文件中的数据插入到mysql数据库中.尝试这样做时,我总是收到这些错误:

I have a data file with the 2nd column in the file being dates in the format '01/01/2007'. I am trying to convert this column into number format so that I can insert the data in the textfile into a mysql database. I keep getting these errors when I try to do so:

Traceback (most recent call last):
  File "C:/Python27/numpy", line 5, in <module>
    x = np.loadtxt(fname='xyz.txt', dtype=[('date', 'str', 12),('x','float')], converters={1:datestr2num}, delimiter=None, skiprows=0, usecols=None);
  File "C:\Python27\lib\site-packages\numpy\lib\npyio.py", line 713, in loadtxt
    X.append(tuple([conv(val) for (conv, val) in zip(converters, vals)]))
  File "C:/Python27/numpy", line 4, in datestr2num
    return datetime.datetime.strptime(s,'"%m/%d/%y"')
  File "C:\Python27\lib\_strptime.py", line 325, in _strptime
    (data_string, format))
ValueError: time data '"01/01/2007"' does not match format '"%m/%d/%y"'

有人可以帮我吗?这是我正在尝试的代码:

Can anyone please help me with this? Here is the code I am trying:

import numpy as np
import datetime
def datestr2num(s):
    return datetime.datetime.strptime(s,'"%m/%d/%y"')
x = np.loadtxt(fname='xyz.txt', dtype= 'float', converters={1:datestr2num}, delimiter=None, skiprows=0, usecols=None);
print x;

推荐答案

'%y'是两位数的年份(例如'14');您有四位数的年份(例如'2014'),因此应该使用'%Y'-请参见文档.

'%y' is for two-digit years (e.g. '14'); you have four-digit years (e.g. '2014') so should be using '%Y' - see the documentation.

这篇关于将文本文件中的日期列转换为浮点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆