【发布时间】:2017-03-16 11:20:00
【问题描述】:
我正在尝试将日期字符串 m/d/YYYY 转换为 datetime.date 对象。我尝试了以下代码,但出现异常。有没有更简单的方法?
从字符串到日期时间日期的日期转换出现格式错误
df_fx = pd.read_csv('data/USDCAD.FXCM_D.txt',delim_whitespace=True, names = ["Date", "Open", "High", "Low", "Close", "Vol"])
格式为#%d/%m/%y,需要转换为DateTime.Date对象类型
strDate = str(df_fx.Date) #%d/%m/%y https://docs.python.org/2/library/datetime.html
r.date = datetime.datetime.strptime(strDate, '%m/%d/%y').date() #stackoverflow.com/questions/466345/converting-string-into-datetime
#note error solution http://stackoverflow.com/questions/12070193/why-is-datetime-strptime-not-working-in-this-simple-example
注意最后一行会产生以下异常:
r.date = datetime.datetime.strptime(strDate, '%m/%d/%y').date() #stackoverflow.com/questions/466345/converting-string-into-datetime
File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data '0 06/13/2006\n1 06/14/2006\n2 ...11/01/2016\nName: Date, dtype: object' does not match format '%m/%d/%y'
我会假设它的格式是错误的,但什么是最好的。我也使用了 %Y 。 谢谢
【问题讨论】: