在Python中查询日期时间对象并与当前日期进行比较

时间:2018-10-30 09:38:46

标签: python datetime sqlite

我有这段代码,我想在当前日期大于SQLite3表中的日期时打印一些内容。

import sqlite3
from datetime import *

conn = sqlite3.connect(":memory:")
c = conn.cursor()

c.execute("CREATE TABLE mutes (name text, seconds int)")
conn.commit()

c.execute("INSERT INTO mutes VALUES (:name, :seconds)", {"name": "William", "seconds": 60})
conn.commit()

while True:
    c.execute("SELECT * FROM mutes WHERE name=:name", {"name":"William"})
    now = datetime.now()
    togo = datetime.now() + timedelta(seconds=int(c.fetchone()[1]))
    if now >= togo:
        print("Release!!!")
        break

我知道它的工作原理是当我反转if语句的条件时,它也会打印出来。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

除非您要减去时间或不增加时间,否则datetime.now()永远不会大于或等于datetime.now() + x

在这种情况下,您要向datetime.now()添加60秒,然后询问datetime.now()是否大于或等于datetime.now() + 60 seconds。这是不可能的。

如果要在当前日期大于测试日期时打印,则测试日期必须为 60秒。

import sqlite3
from datetime import *

conn = sqlite3.connect(":memory:")
c = conn.cursor()

c.execute("CREATE TABLE mutes (name text, seconds int)")
conn.commit()

c.execute("INSERT INTO mutes VALUES (:name, :seconds)", {"name": "William", "seconds": 60})
conn.commit()

while True:
    c.execute("SELECT * FROM mutes WHERE name=:name", {"name":"William"})
    now = datetime.now()
    togo = datetime.now() - timedelta(seconds=int(c.fetchone()[1]))
    if now >= togo:
        print("Release!!!")
        break

如果您希望while True运行60秒,然后再获取breakprint,则可以更改为:     导入sqlite3     从日期时间导入*

conn = sqlite3.connect(":memory:")
c = conn.cursor()

c.execute("CREATE TABLE mutes (name text, seconds int)")
conn.commit()

c.execute("INSERT INTO mutes VALUES (:name, :seconds)", {"name": "William", "seconds": 60})
conn.commit()

c.execute("SELECT * FROM mutes WHERE name=:name", {"name":"William"})
togo = datetime.now() - timedelta(seconds=int(c.fetchone()[1]))

while True:
    now = datetime.now()
    if now >= togo:
        print("Release!!!")
        break