【问题标题】:time data '(datetime.date(2021, 7, 30), )' does not match format '%Y/%m/%d'时间数据 '(datetime.date(2021, 7, 30), )' 与格式 '%Y/%m/%d' 不匹配
【发布时间】:2021-07-30 12:23:59
【问题描述】:

我在 jupyterLab 笔记本中使用以下查询从数据库中访问日期:

newDate = con.cursor()
newDate.execute("select max(CalendarDate) as cdates from db.table1 where cdates < getdate()")
c_date = newDate.fetchone()
cDate = str(c_date)
current_date = datetime.strptime(cDate,'%Y/%m/%d').strftime('%m/%d/%Y')
print(currentdate)

它给出了这个 ValueError: 时间数据 '(datetime.date(2021, 7, 30), )' 与格式 '%Y/%m/%d' 不匹配

谁能指导一下,正确的方法?

【问题讨论】:

  • 为什么会这样? cDate = str(c_date)?您正在将日期转换为字符串("(datetime.date(2021, 7, 30)")。只需保留您的日期,并格式化输出
  • @GiacomoCatenazzi 似乎查询输出以“pyodbc.Row”的形式出现。直接格式化时,报错:AttributeError: 'pyodbc.Row' object has no attribute 'strftime'。
  • 打印它,打印type(c_date),然后试着了解你得到了什么。 (在您的str 之前)。问题就在那里,你试图避免它,但它会再次出现(你在标题中得到的错误)

标签: python sql dataframe python-datetime


【解决方案1】:

似乎c_date 已经是一个 datetime.date 对象。你不需要cDate = str(c_date)

尝试:

newDate = con.cursor()
newDate.execute("select max(CalendarDate) as cdates from db.table1 where cdates < getdate()")
c_date = newDate.fetchval()
current_date = c_date.strftime('%m/%d/%Y')
print(currentdate)

【讨论】:

  • 这是问题所在,当我这样做时,我得到 AttributeError: 'pyodbc.Row' object has no attribute 'strftime'。
  • 哦,我明白了。现在的问题是 fetchone(),尝试用 fetchval() 替换它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-31
  • 2022-01-20
  • 2016-10-15
  • 1970-01-01
  • 2021-10-11
  • 2018-03-18
  • 1970-01-01
相关资源
最近更新 更多