键入String / Int to Date python的类型

时间:2015-12-18 15:51:15

标签: python sql type-conversion

在尝试执行我的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)')

1 个答案:

答案 0 :(得分:0)

在:

 if historical_end_date > caldate.strftime('%Y-%m-%d'):

看起来你正在比较两个字符串。 Python中的Comparing strings与比较时间不同。尝试将你拥有的日期强制转换为日期时间,这样你就可以确定你正在比较那些可以比较的东西。

我说使用strptime()方法:

from datetime import datetime
hist_end_dt = datetime.strptime(historical_end_date,'%Y-%m-%d')
caldate_dt = datetime.strptime(caldate,'%Y-%m-%d')
if hist_end_dt > caldate_dt:
    #do whatever you need to do