我正在尝试将日期字符串m / d / YYYY转换为datetime.date
对象。我尝试下面的代码,但出现异常。有没有更简单的方法?
从字符串到Datetime日期的日期转换时出现格式错误
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。谢谢
我想你想要这样的东西:
import datetime
datetime.datetime.strptime(date_string, '%m/%d/%Y').date()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句