【问题标题】:Type casting of String/Int to Date python类型转换 String/Int 到 Date python
【发布时间】: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


【解决方案1】:

在:

 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

【讨论】:

  • @ciaciode :我尝试使用 strptime() 方法,我得到的错误是无法访问来自 datetime 的 datetime 对象。我正在使用导入语句 s : import datetime\n
  • 我的坏@UdayShankar。为了使我的示例起作用,导入语句应该有所不同。我将编辑答案。让我知道这是否有效。
  • 我不得不同时使用 import 语句:import datetime 和 from datetime import datetime,因此我收到一个错误,即 datetime 内的 datetime 无法访问。有解决办法吗?
  • 鉴于 datetime 被构造为一个包的方式,我认为没有解决方法。不过,最重要的是,您是否通过这种变化实现了自己的目标?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-07
  • 2011-05-22
  • 1970-01-01
  • 2016-05-20
  • 2020-11-09
  • 2017-03-09
  • 1970-01-01
相关资源
最近更新 更多