【问题标题】:Trying to get python sqlite to compare against a DATE and not the actual DATETIME field试图让 python sqlite 与 DATE 而不是实际的 DATETIME 字段进行比较
【发布时间】:2020-12-22 04:50:37
【问题描述】:

我有这段代码不工作...

currentTime = dt.utcnow().date() get just the day has to be UTC cause that what stored in db.
print(currentTime)  #shows day of 2020-09-03
cur = conn.cursor()
cur.execute("SELECT f.user_id, u.first_name, f.location, f.checkin, f.checkout FROM auth_user u JOIN covidlog_onsitelog as f ON (f.user_id=u.id) WHERE CAST(f.checkin as 'DATE()')  = ? or CAST(f.checkout as 'DATE()') =?", (currentTime,currentTime))

该字段是在 django 中作为模型创建的,其中包含以下项目:

2020-09-03 00:40:58.901602

但我只想比较 DAY 而不管时间...虽然它似乎不起作用。

所以对我来说这看起来是正确的,但没有产生结果,所以我只能假设它仍然以某种方式将日期与时间戳进行比较......知道如何不这样做并从字面上与日期进行比较吗?

【问题讨论】:

    标签: sql python-3.x sqlite datetime where-clause


    【解决方案1】:

    检查您的 f.checkin 和 f checkout 字段是否为 datetimestring,在这种情况下,您可以使用 date(f.checkin) 和 date(f.checkout) 而不是 CAST(f.checkin As 'Date()') 您可能想看看“https://stackoverflow.com/questions/4428795/sqlite-convert-string-to-date”和:“https://www.tutlane.com/tutorial/sqlite/sqlite -date-function#:~:text=语法%20of%20SQLite%20date(),datetime%20string%20value%20into%20date.&text=%20SQLite%20date()%20function,YYYY%2DMM%2DDD%20格式。 " 您的 WHERE 子句将如下所示:

    WHERE
        DATE(f.checkin) = ? OR DATE(f.checkout) = ?
    

    【讨论】:

      【解决方案2】:

      你想要date()吗?

      where date(f.checkin) = date(?) or date(f.checkout = date(?)
      

      虽然输入时间有点长,但如果不使用表格列上的日期函数,这可能会更有效地表达:

      where 
          (f.checkin >= date(?) and f.checkin < date(?, '+1 day')
          or (f.checkout >= date(?) and f.checkout < date(?, '+1 day')
      

      【讨论】:

        猜你喜欢
        • 2011-02-15
        • 2018-04-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-31
        • 1970-01-01
        • 2013-07-20
        相关资源
        最近更新 更多