【发布时间】:2016-03-25 09:09:15
【问题描述】:
在尝试执行我的 python 脚本时,我遇到了这些类型转换错误:
historical_start_date = '2015-12-01'
historical_end_date = '2015-12-31'
caldate = 2015-12-10 ## this is date type
sql_str = """SELECT ART_TYPE as ART_TYPE,
year(event_dt) * 100 + month(event_dt) as year_month,
sum(measured_quantity)
FROM <tablename>
WHERE EVENT_DT>=to_date('{1}','YYYY-MM-DD')"""
if historical_end_date > caldate.strftime('%Y-%m-%d'):
sql_str= sql_str+ " AND EVENT_DT<" +caldate.strftime('%Y-%m-%d')
else:
sql_str= sql_str+ " AND EVENT_DT <= to_date('{2}','YYYY-MM-DD') "
sql_str= sql_str+ """ GROUP BY ART_TYPE,year(event_dt) * 100 + month(event_dt)""".format(historical_start_date,historical_end_date)
在运行时,我收到以下错误:
('42883', '[42883] ERROR 4286: Operator does not exist: date < int\nHINT: No operator matches the given name and argument type(s). You may need to add explicit type casts\n (4286) (SQLExecDirectW)')
【问题讨论】:
-
听起来您正在比较日期的
varchar表示与日期的int表示。确保您的数据类型匹配:将类型转换为其他类型。 -
在上面的代码中,我尝试使用 caldate.strftime('%Y-%m-%d') 将 caldate 类型转换为字符串。这是正确的方法吗?我已经尝试过以其他方式使 "=" 两侧的数据类型相等。您能否提供一些日期到 str、str 到日期、int 到日期的转换(语法)示例
-
@Adriano,我在最后给出了整个 sql_str 的 .format。我是否应该为 sql_str 中的每个字符串添加 format(),其中我有一个参数 {0}。我也会尝试按名称使用 {something }
标签: python sql type-conversion