【问题标题】:Convert date string to datetime date but get exception in Python将日期字符串转换为日期时间日期,但在 Python 中出现异常
【发布时间】: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 。 谢谢

【问题讨论】:

    标签: python date datetime


    【解决方案1】:

    你可以只使用python模块datetime

    import datetime
    dt = datetime.datetime.now()
    print(str(dt.day) + " of the " + str(dt.month) + " month of the year " + str(dt.year))
    

    这将以以下格式打印它:

    3 of the 11 month of the year 2016
    

    【讨论】:

    • 感谢 Lachlan,但我在开头重新表述了我正在寻找的问题。
    【解决方案2】:

    我想你想要这样的东西:

    import datetime
    datetime.datetime.strptime(date_string, '%m/%d/%Y').date()
    

    【讨论】:

      猜你喜欢
      • 2015-03-24
      • 2012-06-04
      • 1970-01-01
      • 2015-01-22
      • 2015-09-17
      • 2014-09-21
      • 2021-05-31
      • 2019-04-12
      • 2011-09-08
      相关资源
      最近更新 更多